diff --git a/.env.example b/.env.example index 42ea972..4ac4b13 100644 --- a/.env.example +++ b/.env.example @@ -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: @@ -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= diff --git a/.github/workflows/research-quality-ci.yml b/.github/workflows/research-quality-ci.yml index c27bf15..bfbf1f2 100644 --- a/.github/workflows/research-quality-ci.yml +++ b/.github/workflows/research-quality-ci.yml @@ -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 diff --git a/.gitignore b/.gitignore index a9ce09b..5907b1c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ coverage/ .claude/ apps/backend/debug/ + +# Locally saved Web Data API credentials +apps/backend/.local/ diff --git a/README.md b/README.md index edd5630..bb3159b 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 @@ -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 @@ -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 @@ -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: @@ -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` | @@ -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 @@ -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.? @@ -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 @@ -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 diff --git a/apps/backend/src/features/decodo/decodo.service.spec.ts b/apps/backend/src/features/decodo/decodo.service.spec.ts index dc17876..2b0a27d 100644 --- a/apps/backend/src/features/decodo/decodo.service.spec.ts +++ b/apps/backend/src/features/decodo/decodo.service.spec.ts @@ -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(); }); }); diff --git a/apps/backend/src/features/decodo/decodo.service.ts b/apps/backend/src/features/decodo/decodo.service.ts index 2c88ab6..315ae49 100644 --- a/apps/backend/src/features/decodo/decodo.service.ts +++ b/apps/backend/src/features/decodo/decodo.service.ts @@ -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, { diff --git a/apps/backend/src/features/settings/dto/update-settings.dto.ts b/apps/backend/src/features/settings/dto/update-settings.dto.ts index 30791d5..424e55c 100644 --- a/apps/backend/src/features/settings/dto/update-settings.dto.ts +++ b/apps/backend/src/features/settings/dto/update-settings.dto.ts @@ -1,4 +1,4 @@ -import { IsIn, IsOptional, IsString } from 'class-validator'; +import { IsBoolean, IsIn, IsOptional, IsString, MaxLength } from 'class-validator'; export class UpdateSettingsDto { @IsOptional() @@ -8,4 +8,13 @@ export class UpdateSettingsDto { @IsOptional() @IsString() model?: string; + + @IsOptional() + @IsString() + @MaxLength(4096) + webDataApiKey?: string; + + @IsOptional() + @IsBoolean() + clearWebDataApiKey?: boolean; } diff --git a/apps/backend/src/features/settings/settings.controller.ts b/apps/backend/src/features/settings/settings.controller.ts index b7e43df..229bf99 100644 --- a/apps/backend/src/features/settings/settings.controller.ts +++ b/apps/backend/src/features/settings/settings.controller.ts @@ -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) diff --git a/apps/backend/src/features/settings/settings.module.ts b/apps/backend/src/features/settings/settings.module.ts index 6e4ed5c..b492809 100644 --- a/apps/backend/src/features/settings/settings.module.ts +++ b/apps/backend/src/features/settings/settings.module.ts @@ -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 {} diff --git a/apps/backend/src/features/settings/settings.schema.ts b/apps/backend/src/features/settings/settings.schema.ts index abcb57d..fd4f287 100644 --- a/apps/backend/src/features/settings/settings.schema.ts +++ b/apps/backend/src/features/settings/settings.schema.ts @@ -3,7 +3,7 @@ import { HydratedDocument } from 'mongoose'; export type SettingsDocument = HydratedDocument; -/** 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 */ diff --git a/apps/backend/src/features/settings/settings.service.spec.ts b/apps/backend/src/features/settings/settings.service.spec.ts new file mode 100644 index 0000000..c645d67 --- /dev/null +++ b/apps/backend/src/features/settings/settings.service.spec.ts @@ -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; + 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'); + }); +}); diff --git a/apps/backend/src/features/settings/settings.service.ts b/apps/backend/src/features/settings/settings.service.ts index 584feba..f8b2162 100644 --- a/apps/backend/src/features/settings/settings.service.ts +++ b/apps/backend/src/features/settings/settings.service.ts @@ -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; @@ -18,6 +19,7 @@ export interface SettingsStatus { provider: string; model: string; decodoKeySet: boolean; + decodoKeySource: 'interface' | 'environment' | 'none'; anthropicKeySet: boolean; openaiKeySet: boolean; geminiKeySet: boolean; @@ -31,6 +33,7 @@ export class SettingsService { @InjectModel(Settings.name) private readonly settingsModel: Model, private readonly configService: ConfigService, + private readonly webDataKeyStore: WebDataKeyStore, ) {} async getEffectiveConfig(): Promise { @@ -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 || '', @@ -59,17 +63,30 @@ export class SettingsService { async getStatus(): Promise { 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 { + async update(input: { + provider?: string; + model?: string; + webDataApiKey?: string; + clearWebDataApiKey?: boolean; + }): Promise { + 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 = {}; if (input.provider) patch.provider = input.provider; // Clear model when provider changes so a stale model from another provider isn't used @@ -77,10 +94,18 @@ export class SettingsService { // 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(); } diff --git a/apps/backend/src/features/settings/web-data-key.store.spec.ts b/apps/backend/src/features/settings/web-data-key.store.spec.ts new file mode 100644 index 0000000..0e958c3 --- /dev/null +++ b/apps/backend/src/features/settings/web-data-key.store.spec.ts @@ -0,0 +1,43 @@ +import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { WebDataKeyStore } from './web-data-key.store'; + +describe('WebDataKeyStore', () => { + const originalDirectory = process.env.GITHUB_RESEARCH_DATA_DIR; + let directory: string; + let store: WebDataKeyStore; + + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'github-research-key-')); + process.env.GITHUB_RESEARCH_DATA_DIR = directory; + store = new WebDataKeyStore(); + }); + + afterEach(async () => { + if (originalDirectory === undefined) delete process.env.GITHUB_RESEARCH_DATA_DIR; + else process.env.GITHUB_RESEARCH_DATA_DIR = originalDirectory; + await rm(directory, { recursive: true, force: true }); + }); + + it('returns null before a key has been saved', async () => { + await expect(store.read()).resolves.toBeNull(); + }); + + it('saves and replaces the key in a local file with restrictive permissions', async () => { + await store.save('secret-1'); + expect(await store.read()).toBe('secret-1'); + await store.save('secret-2'); + expect(await readFile(join(directory, 'web-data-api-key'), 'utf8')).toBe('secret-2'); + if (process.platform !== 'win32') { + const permissions = (await stat(join(directory, 'web-data-api-key'))).mode & 0o777; + expect(permissions).toBe(0o600); + } + }); + + it('clears the saved key without creating another credential', async () => { + await store.save('secret'); + await store.clear(); + await expect(store.read()).resolves.toBeNull(); + }); +}); diff --git a/apps/backend/src/features/settings/web-data-key.store.ts b/apps/backend/src/features/settings/web-data-key.store.ts new file mode 100644 index 0000000..4079a3e --- /dev/null +++ b/apps/backend/src/features/settings/web-data-key.store.ts @@ -0,0 +1,46 @@ +import { Injectable } from '@nestjs/common'; +import { randomBytes } from 'node:crypto'; +import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; + +/** + * Local, per-installation credential storage. The key is not stored in MongoDB, + * committed to Git, or returned by the settings API. The backend is designed + * to be accessed locally or behind authentication when self-hosted. + */ +@Injectable() +export class WebDataKeyStore { + private get directory(): string { + return resolve(process.env.GITHUB_RESEARCH_DATA_DIR || join(process.cwd(), '.local')); + } + + private get keyFile(): string { + return join(this.directory, 'web-data-api-key'); + } + + async read(): Promise { + try { + const value = (await readFile(this.keyFile, 'utf8')).trim(); + return value || null; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw error; + } + } + + async save(key: string): Promise { + await mkdir(this.directory, { recursive: true, mode: 0o700 }); + const temporaryFile = `${this.keyFile}.${randomBytes(8).toString('hex')}.tmp`; + try { + await writeFile(temporaryFile, key, { encoding: 'utf8', mode: 0o600, flag: 'wx' }); + await rename(temporaryFile, this.keyFile); + await chmod(this.keyFile, 0o600); + } finally { + await rm(temporaryFile, { force: true }); + } + } + + async clear(): Promise { + await rm(this.keyFile, { force: true }); + } +} diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index 1bb03d2..d732bb5 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -9,7 +9,7 @@ async function bootstrap() { app.enableShutdownHooks(); app.enableCors({ - origin: process.env.PUBLIC_FRONTEND_URL, + origin: process.env.PUBLIC_FRONTEND_URL || 'http://localhost:5274', credentials: true, }); @@ -23,7 +23,7 @@ async function bootstrap() { app.useGlobalFilters(new AllExceptionsFilter()); - await app.listen(process.env.PORT ?? 5002); + await app.listen(process.env.PORT ?? 5002, process.env.HOST || '127.0.0.1'); } void bootstrap(); diff --git a/apps/backend/src/shared/config/config.service.ts b/apps/backend/src/shared/config/config.service.ts index 5b7920a..f49877e 100644 --- a/apps/backend/src/shared/config/config.service.ts +++ b/apps/backend/src/shared/config/config.service.ts @@ -29,7 +29,7 @@ export class ConfigService { get decodo() { return { - authToken: this.configService.get('DECODO_AUTH_TOKEN', ''), + authToken: this.configService.get('DECODO_WEB_DATA_API_KEY', '') || this.configService.get('DECODO_AUTH_TOKEN', ''), scraperEndpoint: this.configService.get('DECODO_SCRAPER_ENDPOINT', 'https://data.decodo.com/v1/scrape'), }; } diff --git a/apps/frontend/src/features/settings/api/useSettingsApi.ts b/apps/frontend/src/features/settings/api/useSettingsApi.ts index c676ea6..293fbee 100644 --- a/apps/frontend/src/features/settings/api/useSettingsApi.ts +++ b/apps/frontend/src/features/settings/api/useSettingsApi.ts @@ -5,6 +5,7 @@ export interface SettingsStatus { provider: string; model: string; decodoKeySet: boolean; + decodoKeySource: 'interface' | 'environment' | 'none'; anthropicKeySet: boolean; openaiKeySet: boolean; geminiKeySet: boolean; @@ -13,6 +14,8 @@ export interface SettingsStatus { export interface UpdateProviderInput { provider?: string; model?: string; + webDataApiKey?: string; + clearWebDataApiKey?: boolean; } const SETTINGS_KEY = ['settings'] as const; diff --git a/apps/frontend/src/routes/_layout/settings.tsx b/apps/frontend/src/routes/_layout/settings.tsx index 9cd6ada..48944d6 100644 --- a/apps/frontend/src/routes/_layout/settings.tsx +++ b/apps/frontend/src/routes/_layout/settings.tsx @@ -12,7 +12,7 @@ import { SelectValue, } from '@/components/ui/select'; import { Skeleton } from '@/components/ui/skeleton'; -import { AlertTriangle, CheckCircle, Circle, Save } from 'lucide-react'; +import { AlertTriangle, CheckCircle, Circle, Save, Trash2 } from 'lucide-react'; import { toast } from 'sonner'; import { useSettingsQuery, @@ -74,6 +74,7 @@ function SettingsPage() { // cascade renders and trip `react-hooks/set-state-in-effect`. const [provider, setProvider] = useState('claude'); const [model, setModel] = useState(''); + const [webDataApiKey, setWebDataApiKey] = useState(''); const [syncedStatus, setSyncedStatus] = useState(null); if (status && status !== syncedStatus) { @@ -105,13 +106,36 @@ function SettingsPage() { ); }; + const handleSaveWebDataKey = () => { + updateMutation.mutate( + { webDataApiKey: webDataApiKey.trim() }, + { + onSuccess: () => { + setWebDataApiKey(''); + toast.success('Web Data API key saved'); + }, + onError: () => toast.error('Failed to save Web Data API key'), + }, + ); + }; + + const handleClearWebDataKey = () => { + updateMutation.mutate( + { clearWebDataApiKey: true }, + { + onSuccess: () => toast.success('Saved Web Data API key cleared'), + onError: () => toast.error('Failed to clear Web Data API key'), + }, + ); + }; + return (

Settings

- Choose your LLM provider. API keys are configured via{' '} - .env on the server. + Choose an LLM provider and configure your Web Data API key. LLM provider keys + remain server environment variables.

@@ -122,8 +146,8 @@ function SettingsPage() {
- DECODO_AUTH_TOKEN is not set in your{' '} - .env — scraping won't work. + Web Data API key is missing. Add it below or set{' '} + DECODO_WEB_DATA_API_KEY in your environment.
)} @@ -216,13 +240,68 @@ function SettingsPage() { - {/* Key status */} + {/* Web Data API credential */} + + + Decodo Web Data API + + Enter your Web Data API key here or configure{' '} + DECODO_WEB_DATA_API_KEY on the server. + Keys entered here are saved locally on the backend, never returned by the API. + + + + +
+ + setWebDataApiKey(e.target.value)} + placeholder={status?.decodoKeySet ? 'Enter a replacement key' : 'Paste your Web Data API key'} + disabled={isLoading || updateMutation.isPending} + /> +

+ Your existing key is never displayed. A key saved here overrides the environment variable. +

+
+
+ + {status?.decodoKeySource === 'interface' && ( + + )} +
+
+
+ + {/* LLM key status */} - API Keys + LLM provider API keys - Set via environment variables in your .env. - Keys are never stored in the database. + Set these through environment variables in your .env. + They are never stored in the database. @@ -241,11 +320,6 @@ function SettingsPage() { isSet={status?.geminiKeySet} isLoading={isLoading} /> -
diff --git a/package.json b/package.json index 67cc5ca..148ca93 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "dev": "bun run --cwd apps/shared build && bunx concurrently \"bun run --cwd apps/backend start:dev\" \"bun run --cwd apps/frontend dev\"", "build": "bun run --cwd apps/shared build && bun run --cwd apps/backend build && bun run --cwd apps/frontend build", "start": "bunx concurrently \"bun run --cwd apps/backend start:prod\" \"bun run --cwd apps/frontend preview\"", - "db:up": "docker-compose up -d", - "db:down": "docker-compose down", + "db:up": "bun scripts/db-compose.mjs up", + "db:down": "bun scripts/db-compose.mjs down", "format": "bun run --cwd apps/backend format && bun run --cwd apps/frontend format" }, "devDependencies": { diff --git a/scripts/db-compose.mjs b/scripts/db-compose.mjs new file mode 100644 index 0000000..9f8a1a8 --- /dev/null +++ b/scripts/db-compose.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +import { spawnSync } from 'node:child_process'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const action = process.argv[2]; +if (action !== 'up' && action !== 'down') { + console.error('Usage: bun db:up | bun db:down'); + process.exit(2); +} + +const choices = [ + { label: 'Podman Compose', program: 'podman', prefix: ['compose'], engine: 'podman' }, + { label: 'Docker Compose', program: 'docker', prefix: ['compose'], engine: 'docker' }, + { label: 'podman-compose', program: 'podman-compose', prefix: [], engine: 'podman' }, + { label: 'docker-compose', program: 'docker-compose', prefix: [], engine: 'docker' }, +]; +const configured = (process.env.CONTAINER_RUNTIME || '').toLowerCase(); +if (configured && !['docker', 'podman'].includes(configured)) { + console.error('CONTAINER_RUNTIME must be docker or podman.'); + process.exit(2); +} + +function works(program, args) { + const result = spawnSync(program, args, { cwd: root, stdio: 'ignore' }); + return !result.error && result.status === 0; +} + +const selected = choices.find((choice) => + (!configured || choice.engine === configured) && + choice.prefix.length > 0 && + works(choice.engine, ['info']) && + works(choice.program, [...choice.prefix, 'version']), +); + +// podman-compose/docker-compose are separate executable names; use their +// native engine to check readiness rather than requiring the wrapper to have +// an 'info' subcommand. +const fallback = !selected && choices.find((choice) => + (!configured || choice.engine === configured) && + choice.prefix.length === 0 && + works(choice.engine, ['info']) && + works(choice.program, ['version']), +); + +const compose = selected || fallback; +if (!compose) { + console.error(`No running container engine with Compose support was found${configured ? ` for ${configured}` : ''}.`); + console.error('Start Docker Desktop or the Podman machine, and install Compose support.'); + console.error('Podman Desktop: Settings → Resources → Compose → Setup.'); + process.exit(1); +} + +console.log(`Using ${compose.label}`); +const args = [...compose.prefix, action, ...(action === 'up' ? ['-d'] : [])]; +const result = spawnSync(compose.program, args, { cwd: root, stdio: 'inherit' }); +if (result.error) console.error(result.error.message); +process.exit(result.status ?? 1);