Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/backend/src/api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,9 @@ import z from 'zod';
import { ConnectionManager } from './connectionManager.js';
import { PromClient } from './promClient.js';
import { RepoIndexManager } from './repoIndexManager.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import { Octokit } from '@octokit/rest';
import { SINGLE_TENANT_ORG_ID } from './constants.js';

const logger = createLogger('api');
const PORT = 3060;
Expand All@@ -33,6 +36,7 @@ export class Api {

app.post('/api/sync-connection', this.syncConnection.bind(this));
app.post('/api/index-repo', this.indexRepo.bind(this));
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
Comment thread
brendan-kellam marked this conversation as resolved.

this.server = app.listen(PORT, () => {
logger.info(`API server is running on port ${PORT}`);
Expand DownExpand Up@@ -92,6 +96,47 @@ export class Api {
res.status(200).json({ jobId });
}

private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
Comment on lines +100 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
cat -n packages/backend/src/api.ts | sed -n '95,110p'

Repository: sourcebot-dev/sourcebot

Length of output: 698


🏁 Script executed:

# Let's also check the full context of this schema usage
cat -n packages/backend/src/api.ts | sed -n '90,120p'

Repository: sourcebot-dev/sourcebot

Length of output: 1265


🌐 Web query:

Zod string trim() min() validation API documentation

💡 Result:

In Zod, both .trim() and .min() are chainable methods on z.string() schemas:

  • .trim(): a transformation that trims leading/trailing whitespace. Example shown in the official “Strings” guide: z.string().trim(); (commented “trim whitespace”). [1]
  • .min(length, options?): a validation that enforces a minimum string length. Example: z.string().min(5); and with a custom message: z.string().min(5, { message: "Must be 5 or more characters long" });. [1]

Typical usage to require a non-empty string after trimming:

import{z}from"zod";constschema=z.string().trim().min(1,{message: "Required"});

(Chaining is the standard Zod API style—e.g., z.string().min(5).max(10).toLowerCase()). [2]

Sources: Zod strings guide [1], Zod v4 package docs [2].


Tighten owner/repo validation.

Empty strings (including whitespace-only strings) currently pass validation and would fail when passed to the GitHub API. Add .trim().min(1) to both fields to validate early and prevent unnecessary API calls.

🔧 Suggested fix
- const schema = z.object({- owner: z.string(),- repo: z.string(),- }).strict();+ const schema = z.object({+ owner: z.string().trim().min(1),+ repo: z.string().trim().min(1),+ }).strict();
📝 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
constschema=z.object({
owner: z.string(),
repo: z.string(),
}).strict();
constschema=z.object({
owner: z.string().trim().min(1),
repo: z.string().trim().min(1),
}).strict();
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 100 - 103, The schema for request
validation (the const schema = z.object({...}).strict()) currently allows empty
or whitespace-only owner/repo strings; update the owner and repo validators to
z.string().trim().min(1) so they reject blank input before calling the GitHub
API, keeping the surrounding z.object(...) and .strict() intact; ensure both the
owner and repo properties are changed.


const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}

const octokit = new Octokit();
const response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});

const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});

const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});

const [jobId ] = await this.repoIndexManager.createJobs([repo], RepoIndexingJobType.INDEX);

res.status(200).json({ jobId, repoId: repo.id });
Comment on lines +111 to +137

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if file exists and view the content around lines 111-137if [ -f"packages/backend/src/api.ts" ];thenecho"File found. Checking lines 111-137:"
sed -n '111,137p' packages/backend/src/api.ts
echo""echo"Broader context (lines 100-150):"
wc -l packages/backend/src/api.ts
elseecho"File not found. Searching for api.ts files:"
find . -name "api.ts" -type f 2>/dev/null | head -20
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1094


🏁 Script executed:

# Check for imports and logger availabilityif [ -f"packages/backend/src/api.ts" ];thenecho"=== Imports and class context ==="
head -50 packages/backend/src/api.ts
fi

Repository: sourcebot-dev/sourcebot

Length of output: 1925


🏁 Script executed:

# Search for existing error handling patterns in the codebaseecho"=== Searching for octokit usage patterns ==="
rg -A 5 "new Octokit" --type ts packages/backend/src/

Repository: sourcebot-dev/sourcebot

Length of output: 805


🌐 Web query:

Octokit JavaScript error handling status codes 404 403 429 rate limit

💡 Result:

In Octokit JS, GitHub API failures are typically thrown as a RequestError with:

  • error.status = HTTP status code
  • error.response = { status, url, headers, data } (when a response exists) (npm.io)

How to interpret / handle the status codes

404 Not Found

  • Resource/route doesn’t exist or GitHub is intentionally hiding a private/inaccessible resource behind a 404 (common pattern). Handle as “missing or not accessible,” and double-check owner/repo names, endpoint, and auth scopes.

403 Forbidden

  • Usually “insufficient permissions / policy” orrate limiting (GitHub may return 403 or 429 when you exceed primary/secondary rate limits). (docs.github.com)
  • For rate limiting, inspect headers and message (see below).

429 Too Many Requests

  • Rate limiting (primary or secondary). GitHub documents that exceeding rate limits can return 403 or 429. (docs.github.com)

Rate limit signals to check (403/429)

GitHub’s guidance when rate-limited: (docs.github.com)

  • x-ratelimit-remaining: 0 ⇒ wait until x-ratelimit-reset (UTC epoch seconds)
  • retry-after (if present) ⇒ wait that many seconds (often for secondary rate limits)
  • Secondary rate limit responses include a message indicating you exceeded a secondary rate limit; if no retry-after, GitHub recommends waiting at least ~60 seconds, then backing off more if it persists. (docs.github.com)

Practical Octokit pattern

try{awaitoctokit.request("GET /repos/{owner}/{repo}",{ owner, repo });}catch(error){if(!error.status)throwerror;// not an Octokit HTTP errorconststatus=error.status;constheaders=error.response?.headers||{};constmessage=error.response?.data?.message;if(status===404){// not found OR not accessible}elseif(status===403||status===429){constremaining=headers["x-ratelimit-remaining"];constreset=headers["x-ratelimit-reset"];constretryAfter=headers["retry-after"];// decide whether this is rate limit vs permissions by checking remaining/message}else{// other HTTP errors}}

Best practice: let Octokit throttle for you

If you want automatic handling/retries for rate limits, use @octokit/plugin-throttling, which provides hooks like onRateLimit and onSecondaryRateLimit and computes retryAfter from retry-after / x-ratelimit-reset. (github.com)

Citations:


Handle GitHub API failures explicitly and prefer authenticated Octokit.

The octokit.rest.repos.get() call at lines 116–119 has no error handling. GitHub API failures will surface as 500s instead of appropriate status codes, and unauthenticated calls are rate-limited to 60 requests/hour (vs. 5000 authenticated), which will cause silent failures. Use a configured GITHUB_TOKEN when available and catch specific status codes (404, 403, 429) to return correct HTTP responses.

🛠️ Proposed handling
- const octokit = new Octokit();- const response = await octokit.rest.repos.get({- owner: parsed.data.owner,- repo: parsed.data.repo,- });+ const octokit = process.env.GITHUB_TOKEN+ ? new Octokit({ auth: process.env.GITHUB_TOKEN })+ : new Octokit();++ let response;+ try {+ response = await octokit.rest.repos.get({+ owner: parsed.data.owner,+ repo: parsed.data.repo,+ });+ } catch (err: any) {+ const status = err?.status;+ if (status === 404) {+ res.status(404).json({ error: 'GitHub repo not found' });+ return;+ }+ if (status === 401 || status === 403) {+ res.status(403).json({ error: 'GitHub access denied' });+ return;+ }+ if (status === 429) {+ res.status(429).json({ error: 'GitHub rate limit exceeded' });+ return;+ }+ logger.error({ err }, 'GitHub API request failed');+ res.status(502).json({ error: 'GitHub API error' });+ return;+ }
🤖 Prompt for AI Agents
In `@packages/backend/src/api.ts` around lines 111 - 137, Replace the
unauthenticated, unhandled GitHub call by instantiating Octokit with
process.env.GITHUB_TOKEN when present (use the Octokit constructor) and wrap the
octokit.rest.repos.get(...) call in a try/catch; on error inspect err.status (or
err.statusCode) and return matching HTTP responses for 404 (res.status(404)),
403 (res.status(403)), and 429 (res.status(429)) with a helpful message, and for
other errors return a 502/500 as appropriate; keep the subsequent
createGitHubRepoRecord(...), prisma.repo.upsert(...) and
repoIndexManager.createJobs(...) logic but only run them after a successful repo
fetch.

}

public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
Expand Down
119 changes: 73 additions & 46 deletions packages/backend/src/repoCompileUtils.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import { GithubConnectionConfig } from '@sourcebot/schemas/v3/github.type';
import { getGitHubReposFromConfig } from "./github.js";
import { getGitHubReposFromConfig, OctokitRepository } from "./github.js";
import { getGitLabReposFromConfig } from "./gitlab.js";
import { getGiteaReposFromConfig } from "./gitea.js";
import { getGerritReposFromConfig } from "./gerrit.js";
Expand DownExpand Up@@ -62,60 +62,23 @@ export const compileGithubConfig = async (
const warnings = gitHubReposResult.warnings;

const hostUrl = config.url ?? 'https://github.com';
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repos = gitHubRepos.map((repo) => {
const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);
const record = createGitHubRepoRecord({
repo,
hostUrl,
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
})

const record: RepoData = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
return {
...record,
connections: {
create: {
connectionId: connectionId,
}
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches: config.revisions?.branches ?? undefined,
tags: config.revisions?.tags ?? undefined,
} satisfies RepoMetadata,
};

return record;
})

return {
Expand All@@ -124,6 +87,70 @@ export const compileGithubConfig = async (
};
}

export const createGitHubRepoRecord = ({
repo,
hostUrl,
branches,
tags,
isAutoCleanupDisabled,
}: {
repo: OctokitRepository,
hostUrl: string,
branches?: string[],
tags?: string[],
isAutoCleanupDisabled?: boolean,
}) => {
const repoNameRoot = new URL(hostUrl)
.toString()
.replace(/^https?:\/\//, '');

const repoDisplayName = repo.full_name;
const repoName = path.join(repoNameRoot, repoDisplayName);
const cloneUrl = new URL(repo.clone_url!);
const isPublic = repo.private === false;

logger.debug(`Found github repo ${repoDisplayName} with webUrl: ${repo.html_url}`);

const record: Prisma.RepoCreateInput = {
external_id: repo.id.toString(),
external_codeHostType: 'github',
external_codeHostUrl: hostUrl,
cloneUrl: cloneUrl.toString(),
webUrl: repo.html_url,
name: repoName,
displayName: repoDisplayName,
imageUrl: repo.owner.avatar_url,
isFork: repo.fork,
isArchived: !!repo.archived,
isPublic: isPublic,
isAutoCleanupDisabled,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
},
},
metadata: {
gitConfig: {
'zoekt.web-url-type': 'github',
'zoekt.web-url': repo.html_url,
'zoekt.name': repoName,
'zoekt.github-stars': (repo.stargazers_count ?? 0).toString(),
'zoekt.github-watchers': (repo.watchers_count ?? 0).toString(),
'zoekt.github-subscribers': (repo.subscribers_count ?? 0).toString(),
'zoekt.github-forks': (repo.forks_count ?? 0).toString(),
'zoekt.archived': marshalBool(repo.archived),
'zoekt.fork': marshalBool(repo.fork),
'zoekt.public': marshalBool(isPublic),
'zoekt.display-name': repoDisplayName,
},
branches,
tags,
} satisfies RepoMetadata,
};

return record;
}

export const compileGitlabConfig = async (
config: GitlabConnectionConfig,
connectionId: number): Promise<CompileResult> => {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/repoIndexManager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,6 +160,7 @@ export class RepoIndexManager {
connections: {
none: {}
},
isAutoCleanupDisabled: false,
OR: [
{ indexedAt: null },
{ indexedAt: { lt: gcGracePeriodMs } },
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Repo" ADD COLUMN "isAutoCleanupDisabled" BOOLEAN NOT NULL DEFAULT false;
Comment thread
brendan-kellam marked this conversation as resolved.
27 changes: 14 additions & 13 deletions packages/db/prisma/schema.prisma
Original file line numberDiff line numberDiff line change
Expand Up@@ -45,19 +45,20 @@ enum CodeHostType {
}

model Repo {
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?
id Int @id @default(autoincrement())
name String /// Full repo name, including the vcs hostname (ex. github.com/sourcebot-dev/sourcebot)
displayName String? /// Display name of the repo for UI (ex. sourcebot-dev/sourcebot)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isFork Boolean
isArchived Boolean
isPublic Boolean @default(false)
isAutoCleanupDisabled Boolean @default(false) /// If true, automatic cleanup of this repo when it becomes orphaned will be disabled.
metadata Json /// For schema see repoMetadataSchema in packages/shared/src/types.ts
cloneUrl String
webUrl String?
connections RepoToConnection[]
imageUrl String?

permittedAccounts AccountToRepoPermission[]
permissionSyncJobs RepoPermissionSyncJob[]
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/env.server.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -196,6 +196,7 @@ export const env = createEnv({
// @NOTE: Take care to update actions.ts when changing the name of this.
EXPERIMENT_SELF_SERVE_REPO_INDEXING_GITHUB_TOKEN: z.string().optional(),
EXPERIMENT_EE_PERMISSION_SYNC_ENABLED: booleanSchema.default('false'),
EXPERIMENT_ASK_GH_ENABLED: booleanSchema.default('false'),

SOURCEBOT_ENCRYPTION_KEY: z.string(),
SOURCEBOT_INSTALL_ID: z.string().default("unknown"),
Expand Down
34 changes: 34 additions & 0 deletions packages/web/src/app/[domain]/askgh/[owner]/[repo]/api.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { sew } from '@/actions';
import { notFound, ServiceError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { RepoInfo } from './types';

export const getRepoInfo = async (repoId: number): Promise<RepoInfo | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ prisma }) => {
const repo = await prisma.repo.findUnique({
where: { id: repoId },
include: {
jobs: {
orderBy: {
createdAt: 'desc',
},
take: 1,
},
},
});

if (!repo) {
return notFound();
}

return {
id: repo.id,
name: repo.name,
displayName: repo.displayName,
imageUrl: repo.imageUrl,
isIndexed: repo.indexedAt !== null,
};
})
)
Loading