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
11 changes: 9 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ MONGO_PORT=27018
MONGODB_URI=mongodb://localhost:27018/github-research

# Decodo Web Data API
# Paste your Web Data API key only (without the "Bearer" prefix).
DECODO_AUTH_TOKEN=
# Optional: configure the key here OR enter it on the Settings page.
# Paste the key only, without the "Bearer" prefix.
DECODO_WEB_DATA_API_KEY=
DECODO_SCRAPER_ENDPOINT=https://data.decodo.com/v1/scrape

# GitHub requests always use:
Expand All @@ -25,3 +26,9 @@ GEMINI_API_KEY=

# Optional: number of repositories enriched through additional Web Data API calls (0–12; default 6)
GITHUB_METADATA_ENRICH_LIMIT=6

# Optional. Backend binds to localhost by default. Use another host only
# behind an authenticated proxy when serving remotely.
HOST=127.0.0.1
# Optional directory for the locally saved Web Data API key.
# GITHUB_RESEARCH_DATA_DIR=
2 changes: 1 addition & 1 deletion .github/workflows/research-quality-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ jobs:
- name: Typecheck backend
run: bunx tsc --noEmit -p apps/backend/tsconfig.json
- name: Run research regression tests
run: bun run --cwd apps/backend test --runInBand --runTestsByPath src/features/research/research-insights.spec.ts src/features/github/github-parser.service.spec.ts
run: bun run --cwd apps/backend test --runInBand --runTestsByPath src/features/research/research-insights.spec.ts src/features/github/github-parser.service.spec.ts src/features/settings/web-data-key.store.spec.ts src/features/settings/settings.service.spec.ts
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ coverage/
.claude/

apps/backend/debug/

# Locally saved Web Data API credentials
apps/backend/.local/
31 changes: 19 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ The current research flow does **not** use the GitHub REST API as its data sourc
Before installing the project, make sure you have:

- [Bun](https://bun.sh) 1.2.5 or newer
- [Docker](https://docker.com) or another Docker-compatible runtime
- [Docker Desktop](https://docker.com) with Compose, [Podman Desktop](https://podman-desktop.io/) with Compose, or an existing MongoDB server
- A Decodo Web Data API key – [create a Decodo account](https://dashboard.decodo.com/register)
- At least one supported LLM provider API key:
- Anthropic
Expand Down Expand Up @@ -104,7 +104,7 @@ Files beginning with a dot may be hidden by default. If you don't see `.env` in
- On most Linux file managers, press **Ctrl**+**H**
- On Windows, use **View** → **Show** → **Hidden items** if needed

Open `.env` and add your Decodo Web Data API key, select an LLM provider, and add the API key for that provider.
Open `.env`, select your LLM provider, and add its API key. You can configure the Decodo Web Data API key here or enter it later on the **Settings** page.

```env
# Backend
Expand All @@ -117,8 +117,8 @@ MONGO_PORT=27018
MONGODB_URI=mongodb://localhost:27018/github-research

# Decodo Web Data API
# Paste your Web Data API key only, without the "Bearer" prefix.
DECODO_AUTH_TOKEN=
# Optional: paste the key without the "Bearer" prefix, or enter it in Settings.
DECODO_WEB_DATA_API_KEY=
DECODO_SCRAPER_ENDPOINT=https://data.decodo.com/v1/scrape

# LLM provider: claude | openai | gemini
Expand All @@ -134,13 +134,15 @@ Only the API key for the selected `LLM_PROVIDER` is required. `LLM_MODEL` is opt

### 4. Start MongoDB

Make sure Docker is running, then start the local MongoDB container:
Start Docker Desktop or your Podman machine, with Compose support enabled, then start the local MongoDB container:

```bash
bun db:up
```

If Docker reports that port `27018` is already allocated, another MongoDB container or service is already using that host port. Stop the conflicting service or change both `MONGO_PORT` and the port in `MONGODB_URI`.
The command automatically detects a running Docker or Podman engine and a compatible Compose provider. You do not need the legacy `docker-compose` command. For Podman Desktop, install the **Compose** extension through **Settings → Resources → Compose → Setup** if it is missing. Use `CONTAINER_RUNTIME=podman bun db:up` to explicitly prefer Podman when both engines are installed. The matching `bun db:down` command stops the container.

If you already have MongoDB running, you can skip `bun db:up` and set `MONGODB_URI` to its connection string. MongoDB remains the required database; the container runtime is interchangeable. If port `27018` is occupied, stop the conflicting service or change `MONGO_PORT` together with `MONGODB_URI`.

### 5. Build the application

Expand All @@ -154,7 +156,7 @@ bun run build
bun dev
```

Keep the terminal window open while using the application. Closing it stops the local frontend and backend.
Keep the terminal window open while using the application. Closing it stops the local frontend and backend. After startup, open **Settings** to save a Web Data API key if you did not configure one in `.env`.

Frontend:

Expand Down Expand Up @@ -265,11 +267,14 @@ The comparison describes each product's main workflow. These tools solve overlap
| Variable | Description |
| --- | --- |
| `PORT` | Backend port. Defaults to `5002` |
| `HOST` | Backend bind address. Defaults to `127.0.0.1` for local use |
| `CONTAINER_RUNTIME` | Optional `podman` or `docker` preference for the database scripts |
| `GITHUB_RESEARCH_DATA_DIR` | Optional directory for the locally saved Web Data API key; defaults to the backend's `.local` directory |
| `PUBLIC_API_BASE_URL` | API URL used by the frontend |
| `PUBLIC_FRONTEND_URL` | Frontend URL used by the application |
| `MONGO_PORT` | Host port mapped to the MongoDB container |
| `MONGODB_URI` | MongoDB connection string |
| `DECODO_AUTH_TOKEN` | Decodo Web Data API key, without the `Bearer` prefix |
| `DECODO_WEB_DATA_API_KEY` | Optional Decodo Web Data API key, without the `Bearer` prefix. Alternatively save it in Settings. The old `DECODO_AUTH_TOKEN` is supported as a fallback |
| `DECODO_SCRAPER_ENDPOINT` | Decodo scraping endpoint. The included default is normally sufficient |
| `GITHUB_METADATA_ENRICH_LIMIT` | Optional maximum repository-page metadata enrichment requests per run (default: 6; maximum: 12; 0 disables) |
| `LLM_PROVIDER` | LLM provider: `claude`, `openai`, or `gemini` |
Expand All @@ -278,7 +283,9 @@ The comparison describes each product's main workflow. These tools solve overlap
| `OPENAI_API_KEY` | OpenAI API key |
| `GEMINI_API_KEY` | Google Gemini API key |

The **Settings** page can change the active LLM provider and optional model override. API keys, including the Decodo Web Data API key, remain environment variables and are never returned by the settings API.
The **Settings** page lets users select their LLM provider/model and enter or replace the **Decodo Web Data API key**. An interface-entered key takes precedence over the environment variable. It is stored in a local, Git-ignored backend file (`apps/backend/.local/web-data-api-key` when using `bun dev`) with restrictive filesystem permissions, not in MongoDB. API responses return only a configured indicator and source; they never return the secret. Clearing the saved key restores the environment-variable fallback. LLM provider keys remain environment variables.

**Security note:** The application defaults to a loopback-only backend (`HOST=127.0.0.1`). The settings API is not an authenticated multi-user secrets manager. For remote deployments, put it behind an authenticated reverse proxy and secure the host and credential file. Back up the local credential file separately if required.

### Research filters

Expand Down Expand Up @@ -349,7 +356,7 @@ GitHub documents a primary REST API limit of **60 requests per hour for unauthen

### Do I need a Decodo account?

Yes. GitHub Research retrieves its GitHub source pages through Decodo Web Data API, so you need a [Decodo account](https://dashboard.decodo.com/) and a valid Web Data API key. The API key is supplied through `DECODO_AUTH_TOKEN` in your local `.env` file and is not exposed by the application's Settings API.
Yes. GitHub Research retrieves its GitHub source pages through Decodo Web Data API, so you need a [Decodo account](https://dashboard.decodo.com/) and a valid Web Data API key. Set `DECODO_WEB_DATA_API_KEY` in `.env` or enter the key on the Settings page. The earlier `DECODO_AUTH_TOKEN` is still accepted for compatibility. The Settings API never returns the key itself.

### Is GitHub Research affiliated with GitHub, Inc.?

Expand All @@ -369,7 +376,7 @@ Yes. GitHub Research is designed to run locally or on an always-on host with Bun
| Parsing | Cheerio and deterministic GitHub parsers |
| LLMs | Anthropic Claude, OpenAI GPT, Google Gemini |
| Runtime | Bun |
| Local services | Docker Compose, MongoDB |
| Local services | MongoDB, Docker or Podman with Compose |

## Project structure

Expand Down Expand Up @@ -408,7 +415,7 @@ docs/
| `bun start` | Start the production backend and frontend preview server |
| `bun lint` | Run linting across frontend and backend |
| `bun format` | Format frontend and backend source files |
| `bun db:up` | Start MongoDB through Docker Compose |
| `bun db:up` | Start MongoDB using an available Docker or Podman Compose provider |
| `bun db:down` | Stop the local database container |

## Related repositories
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/features/decodo/decodo.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ describe('DecodoService', () => {
} as unknown as SettingsService;
service = new DecodoService(settingsService);

await expect(service.scrapeUrl(githubUrl)).rejects.toThrow('DECODO_AUTH_TOKEN must be configured.');
await expect(service.scrapeUrl(githubUrl)).rejects.toThrow('Web Data API key is missing. Add it in Settings or set DECODO_WEB_DATA_API_KEY.');
expect(fetchSpy).not.toHaveBeenCalled();
});
});
2 changes: 1 addition & 1 deletion apps/backend/src/features/decodo/decodo.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class DecodoService {

const config = await this.settingsService.getEffectiveConfig();
if (!config.decodoAuthToken) {
throw new BadRequestException('DECODO_AUTH_TOKEN must be configured.');
throw new BadRequestException('Web Data API key is missing. Add it in Settings or set DECODO_WEB_DATA_API_KEY.');
}

const response = await fetch(config.decodoScraperEndpoint, {
Expand Down
11 changes: 10 additions & 1 deletion apps/backend/src/features/settings/dto/update-settings.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IsIn, IsOptional, IsString } from 'class-validator';
import { IsBoolean, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';

export class UpdateSettingsDto {
@IsOptional()
Expand All @@ -8,4 +8,13 @@ export class UpdateSettingsDto {
@IsOptional()
@IsString()
model?: string;

@IsOptional()
@IsString()
@MaxLength(4096)
webDataApiKey?: string;

@IsOptional()
@IsBoolean()
clearWebDataApiKey?: boolean;
}
2 changes: 1 addition & 1 deletion apps/backend/src/features/settings/settings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class SettingsController {

/**
* PATCH /settings
* Updates provider and/or model preference. API keys cannot be set here.
* Updates provider/model preferences and optionally the local Web Data API key.
*/
@Patch()
@HttpCode(HttpStatus.OK)
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/features/settings/settings.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { MongooseModule } from '@nestjs/mongoose';
import { SettingsController } from './settings.controller';
import { SettingsService } from './settings.service';
import { Settings, SettingsSchema } from './settings.schema';
import { WebDataKeyStore } from './web-data-key.store';

@Module({
imports: [MongooseModule.forFeature([{ name: Settings.name, schema: SettingsSchema }])],
controllers: [SettingsController],
providers: [SettingsService],
providers: [SettingsService, WebDataKeyStore],
exports: [SettingsService],
})
export class SettingsModule {}
2 changes: 1 addition & 1 deletion apps/backend/src/features/settings/settings.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HydratedDocument } from 'mongoose';

export type SettingsDocument = HydratedDocument<Settings>;

/** Stores user-selected LLM preferences. API keys are never stored here. */
/** Stores user-selected LLM preferences. API keys are stored separately. */
@Schema({ timestamps: true })
export class Settings {
/** Always 'global' — only one settings document exists */
Expand Down
59 changes: 59 additions & 0 deletions apps/backend/src/features/settings/settings.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Model } from 'mongoose';
import type { ConfigService } from '../../shared/config/config.service';
import { SettingsService } from './settings.service';
import type { SettingsDocument } from './settings.schema';
import { WebDataKeyStore } from './web-data-key.store';

describe('SettingsService Web Data API key', () => {
const oldDirectory = process.env.GITHUB_RESEARCH_DATA_DIR;
let directory: string;
let store: WebDataKeyStore;
let service: SettingsService;
const findOneAndUpdate = jest.fn();

beforeEach(async () => {
directory = await mkdtemp(join(tmpdir(), 'github-research-settings-'));
process.env.GITHUB_RESEARCH_DATA_DIR = directory;
store = new WebDataKeyStore();
findOneAndUpdate.mockClear();
const model = {
findOne: () => ({ exec: async () => null }),
findOneAndUpdate,
} as unknown as Model<SettingsDocument>;
const config = {
llm: { provider: 'claude', model: '', anthropicApiKey: 'llm-secret', openaiApiKey: '', geminiApiKey: '' },
decodo: { authToken: 'environment-key', scraperEndpoint: 'https://data.decodo.com/v1/scrape' },
} as unknown as ConfigService;
service = new SettingsService(model, config, store);
});

afterEach(async () => {
if (oldDirectory === undefined) delete process.env.GITHUB_RESEARCH_DATA_DIR;
else process.env.GITHUB_RESEARCH_DATA_DIR = oldDirectory;
await rm(directory, { recursive: true, force: true });
});

it('accepts an interface key, gives it precedence and never returns the value in status', async () => {
const status = await service.update({ webDataApiKey: 'interface-secret' });
expect(status.decodoKeySource).toBe('interface');
expect(status.decodoKeySet).toBe(true);
expect(JSON.stringify(status)).not.toContain('interface-secret');
expect((await service.getEffectiveConfig()).decodoAuthToken).toBe('interface-secret');
expect(findOneAndUpdate).not.toHaveBeenCalled();
});

it('falls back to the environment key after the saved key is cleared', async () => {
await service.update({ webDataApiKey: 'interface-secret' });
const status = await service.update({ clearWebDataApiKey: true });
expect(status.decodoKeySource).toBe('environment');
expect((await service.getEffectiveConfig()).decodoAuthToken).toBe('environment-key');
});

it('rejects a blank key or simultaneous save and clear', async () => {
await expect(service.update({ webDataApiKey: ' ' })).rejects.toThrow('cannot be blank');
await expect(service.update({ webDataApiKey: 'secret', clearWebDataApiKey: true })).rejects.toThrow('same request');
});
});
41 changes: 33 additions & 8 deletions apps/backend/src/features/settings/settings.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Injectable, Logger } from '@nestjs/common';
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ConfigService } from '../../shared/config/config.service';
import { Settings, SettingsDocument } from './settings.schema';
import { WebDataKeyStore } from './web-data-key.store';

export interface EffectiveConfig {
provider: string;
Expand All @@ -18,6 +19,7 @@ export interface SettingsStatus {
provider: string;
model: string;
decodoKeySet: boolean;
decodoKeySource: 'interface' | 'environment' | 'none';
anthropicKeySet: boolean;
openaiKeySet: boolean;
geminiKeySet: boolean;
Expand All @@ -31,6 +33,7 @@ export class SettingsService {
@InjectModel(Settings.name)
private readonly settingsModel: Model<SettingsDocument>,
private readonly configService: ConfigService,
private readonly webDataKeyStore: WebDataKeyStore,
) {}

async getEffectiveConfig(): Promise<EffectiveConfig> {
Expand All @@ -43,13 +46,14 @@ export class SettingsService {

const envLlm = this.configService.llm;
const envDecodo = this.configService.decodo;
const localKey = await this.webDataKeyStore.read();

return {
// Provider and model: DB selection overrides env, env overrides default
provider: doc?.provider || envLlm.provider || 'claude',
model: doc?.model || envLlm.model || '',
// API keys: always from env only, never from DB
decodoAuthToken: envDecodo.authToken || '',
// UI-entered key takes precedence. Both sources remain server-side.
decodoAuthToken: localKey || envDecodo.authToken || '',
decodoScraperEndpoint: envDecodo.scraperEndpoint || 'https://data.decodo.com/v1/scrape',
anthropicApiKey: envLlm.anthropicApiKey || '',
openaiApiKey: envLlm.openaiApiKey || '',
Expand All @@ -59,28 +63,49 @@ export class SettingsService {

async getStatus(): Promise<SettingsStatus> {
const config = await this.getEffectiveConfig();
const localKey = await this.webDataKeyStore.read();
return {
provider: config.provider,
model: config.model,
decodoKeySet: !!config.decodoAuthToken,
decodoKeySource: localKey ? 'interface' : config.decodoAuthToken ? 'environment' : 'none',
anthropicKeySet: !!config.anthropicApiKey,
openaiKeySet: !!config.openaiApiKey,
geminiKeySet: !!config.geminiApiKey,
};
}

async update(input: { provider?: string; model?: string }): Promise<SettingsStatus> {
async update(input: {
provider?: string;
model?: string;
webDataApiKey?: string;
clearWebDataApiKey?: boolean;
}): Promise<SettingsStatus> {
if (input.webDataApiKey !== undefined && input.clearWebDataApiKey) {
throw new BadRequestException('Cannot set and clear the Web Data API key in the same request.');
}
if (input.webDataApiKey !== undefined && !input.webDataApiKey.trim()) {
throw new BadRequestException('Web Data API key cannot be blank. Use Clear saved key instead.');
}
const patch: Record<string, string> = {};
if (input.provider) patch.provider = input.provider;
// Clear model when provider changes so a stale model from another provider isn't used
if (input.provider) patch.model = '';
// Allow explicit model override (empty string resets to provider default)
if (input.model !== undefined) patch.model = input.model.trim();

this.logger.log(`[Settings] Updating: ${JSON.stringify(patch)}`);
await this.settingsModel
.findOneAndUpdate({ key: 'global' }, { $set: patch }, { upsert: true, new: true })
.exec();
if (Object.keys(patch).length) {
this.logger.log('[Settings] Updating provider/model preferences');
await this.settingsModel
.findOneAndUpdate({ key: 'global' }, { $set: patch }, { upsert: true, new: true })
.exec();
}

if (input.webDataApiKey !== undefined) {
await this.webDataKeyStore.save(input.webDataApiKey.trim());
} else if (input.clearWebDataApiKey) {
await this.webDataKeyStore.clear();
}

return this.getStatus();
}
Expand Down
Loading
Loading