feat(web,ui): per-project forced git provider and settings gating
Adds a per-project forced provider (github|gitlab|gitea) on top of the per-project API base URL overrides: stored under gitProviders.provider in projects/<projectId>.json, sanitized server-side, and winning over remote-host detection both in useGitProvider and in server repo resolution (parseGitLabRemoteUrl/parseGiteaRemoteUrl accept any host when the provider is forced). The Projects settings page replaces the three always-visible URL fields with a provider selector (auto-detect + the three forges) and one URL override for the active provider. Global provider override fields on the GitHub/GitLab/Gitea settings tabs now render only once an account is connected, and Settings search availability matches that gating. Also fixes the useConfigStore/useDirectoryStore circular-import TDZ in the bundled chunk via the window-registered store handle and defers the directory subscription to a microtask; fixes the Gitea PR merge payload (Do carries the merge-style string enum, not a boolean + MergeMethod); and adds a documented Gitea client live-test harness (scripts/gitea-live-test.ts + client.d.ts).
This commit is contained in:
@@ -27,11 +27,13 @@
|
||||
## Public exports — `project-config.js`
|
||||
|
||||
- `OPENCHAMBER_PROJECTS_DIR`: `path.join(OPENCHAMBER_DATA_DIR, 'projects')` (same `OPENCHAMBER_DATA_DIR` env logic as `config.js`).
|
||||
- `sanitizeProjectGitProviders(payload)`: same provider allowlist/`normalizeBaseUrl` rules as `sanitizeGitProviders`, but the per-project shape only carries `apiBaseUrl` (`detectUrls` tolerated and stripped); `undefined` when nothing valid remains.
|
||||
- `sanitizeProjectGitProviders(payload)`: same provider allowlist/`normalizeBaseUrl` rules as `sanitizeGitProviders`, but the per-project shape only carries `apiBaseUrl` (`detectUrls` tolerated and stripped) plus an optional forced `provider` (`github|gitlab|gitea`, normalized lowercase; unknown values dropped); `undefined` when nothing valid remains.
|
||||
- `readProjectJson(projectId)`: raw JSON object from `projects/<projectId>.json`; `{}` on missing/malformed file, `null` for an invalid projectId; never throws.
|
||||
- `getProjectGitProviders(projectId)`: effective per-project overrides (`{}` when unset or invalid projectId).
|
||||
- `resolveProjectIdFromDirectory(directory)`: projectId for a directory — worktree-aware: the directory is first resolved to its main repo root via `git rev-parse --git-common-dir` (handles linked worktrees created outside the project root, and a project rooted at the filesystem `/`), then the longest matching project path from the settings.json `projects` list that equals it or is a path-prefix wins; when git is unavailable or the directory is not a git repo, the directory's own exact/containment match applies; fallback `createProjectIdFromPath(directory)`; `null` for empty input. Results are cached per-directory for 60s (TTL cache, negative results included) so forge hot paths don't exec git / re-read settings.json per request. `_clearResolveProjectIdCache()` is a test-only hook to drop the cache.
|
||||
- `getProjectProviderApiBaseUrl(provider, projectId)`: per-project `apiBaseUrl` override or `null`.
|
||||
- `getProjectProvider(projectId)`: the project's forced provider (`github|gitlab|gitea`) or `null` when auto-detected.
|
||||
- `getProjectProviderFromDirectory(directory)`: forced provider for a directory's owning project (via `resolveProjectIdFromDirectory` → `getProjectProvider`), or `null`.
|
||||
- `getEffectiveProviderApiBaseUrl(provider, directory)`: project override -> `getProviderApiBaseUrl(provider)` (global -> built-in default); `null` only when nothing resolves.
|
||||
- `saveProjectGitProviders(projectId, payload)`: persist the per-project overrides, preserving all other project JSON keys (atomic tmp-file + rename write); returns the saved `gitProviders` object (or `{}`); throws for an invalid projectId.
|
||||
|
||||
@@ -65,6 +67,7 @@
|
||||
"version": 1,
|
||||
"projectNotes": "...",
|
||||
"gitProviders": {
|
||||
"provider": "gitlab",
|
||||
"github": { "apiBaseUrl": "https://project.github.example.com" },
|
||||
"gitlab": { "apiBaseUrl": "https://project.gitlab.example.com" }
|
||||
}
|
||||
@@ -72,6 +75,7 @@
|
||||
```
|
||||
|
||||
- Per-project `gitProviders` carry `apiBaseUrl` only (no `detectUrls`); unknown provider keys are dropped and `apiBaseUrl` is normalized with the same rules as the global settings.
|
||||
- Optional `provider` (`github|gitlab|gitea`) forces the project's git provider instead of auto-detection. Client-side, a forced provider short-circuits remote-host detection (`useGitProvider`); server-side, it makes any remote host acceptable for that provider's repo parsing (`gitlab/repo.js`, `gitea/repo.js`).
|
||||
- `projects/<projectId>.json` is shared with the scheduled-tasks/projectNotes config; reading and saving preserve all other keys (the `gitProviders` key is omitted entirely when empty).
|
||||
- **Precedence per provider:** project override (`projects/<projectId>.json` → `getProjectProviderApiBaseUrl`) > global `settings.json` (`getProviderApiBaseUrl`) > built-in default (`GIT_PROVIDER_DEFAULTS`).
|
||||
|
||||
|
||||
@@ -30,26 +30,35 @@ const normalizeProjectPathForMatch = (value) => {
|
||||
return value.replace(/\\/g, '/').replace(/\/+$/g, '') || value;
|
||||
};
|
||||
|
||||
const GIT_PROVIDER_SET = new Set(['github', 'gitlab', 'gitea']);
|
||||
|
||||
/**
|
||||
* Validate/normalize a per-project `gitProviders` value. Same provider
|
||||
* allowlist and `normalizeBaseUrl` rules as `sanitizeGitProviders`, but the
|
||||
* per-project shape only carries `apiBaseUrl` (any `detectUrls` are tolerated
|
||||
* and stripped). Returns undefined when nothing valid remains.
|
||||
* and stripped) plus an optional forced `provider` (github|gitlab|gitea) that
|
||||
* overrides automatic provider detection for the project. Returns undefined
|
||||
* when nothing valid remains.
|
||||
*/
|
||||
export function sanitizeProjectGitProviders(payload) {
|
||||
const sanitized = sanitizeGitProviders(payload);
|
||||
if (!sanitized) {
|
||||
return undefined;
|
||||
}
|
||||
const result = {};
|
||||
for (const provider of Object.keys(sanitized)) {
|
||||
const entry = sanitized[provider];
|
||||
const normalized = {};
|
||||
if (entry.apiBaseUrl) {
|
||||
normalized.apiBaseUrl = entry.apiBaseUrl;
|
||||
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
||||
const forcedProvider = typeof payload.provider === 'string' ? payload.provider.trim().toLowerCase() : '';
|
||||
if (GIT_PROVIDER_SET.has(forcedProvider)) {
|
||||
result.provider = forcedProvider;
|
||||
}
|
||||
if (Object.keys(normalized).length > 0) {
|
||||
result[provider] = normalized;
|
||||
}
|
||||
const sanitized = sanitizeGitProviders(payload);
|
||||
if (sanitized) {
|
||||
for (const provider of Object.keys(sanitized)) {
|
||||
const entry = sanitized[provider];
|
||||
const normalized = {};
|
||||
if (entry.apiBaseUrl) {
|
||||
normalized.apiBaseUrl = entry.apiBaseUrl;
|
||||
}
|
||||
if (Object.keys(normalized).length > 0) {
|
||||
result[provider] = normalized;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Object.keys(result).length > 0 ? result : undefined;
|
||||
@@ -270,6 +279,28 @@ export function getProjectProviderApiBaseUrl(provider, projectId) {
|
||||
return getProjectGitProviders(projectId)[provider]?.apiBaseUrl || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The project's forced git provider (github|gitlab|gitea), or null when the
|
||||
* provider is auto-detected from the remote. Only meaningful for a projectId
|
||||
* that resolves to a project config; invalid ids yield null.
|
||||
*/
|
||||
export function getProjectProvider(projectId) {
|
||||
const providers = getProjectGitProviders(projectId);
|
||||
return providers.provider || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The forced git provider for a directory's owning project, or null when
|
||||
* unset or when the directory resolves to no project.
|
||||
*/
|
||||
export function getProjectProviderFromDirectory(directory) {
|
||||
const projectId = resolveProjectIdFromDirectory(directory);
|
||||
if (!projectId) {
|
||||
return null;
|
||||
}
|
||||
return getProjectProvider(projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective API base URL for a provider given a directory: the project override
|
||||
* (when the directory resolves to a project with one) wins, else the global
|
||||
|
||||
@@ -12,6 +12,8 @@ process.env.OPENCHAMBER_DATA_DIR = TEMP_DATA_DIR;
|
||||
const {
|
||||
sanitizeProjectGitProviders,
|
||||
getProjectGitProviders,
|
||||
getProjectProvider,
|
||||
getProjectProviderFromDirectory,
|
||||
resolveProjectIdFromDirectory,
|
||||
getProjectProviderApiBaseUrl,
|
||||
getEffectiveProviderApiBaseUrl,
|
||||
@@ -73,6 +75,46 @@ describe('sanitizeProjectGitProviders', () => {
|
||||
expect(sanitizeProjectGitProviders([])).toBeUndefined();
|
||||
expect(getProjectGitProviders('proj_1')).toEqual({});
|
||||
});
|
||||
|
||||
test('keeps a forced provider when it is one of the known providers', () => {
|
||||
expect(sanitizeProjectGitProviders({
|
||||
provider: 'GitLab',
|
||||
gitlab: { apiBaseUrl: 'gitlab.example.com' },
|
||||
})).toEqual({
|
||||
provider: 'gitlab',
|
||||
gitlab: { apiBaseUrl: 'https://gitlab.example.com' },
|
||||
});
|
||||
});
|
||||
|
||||
test('drops an unknown or empty forced provider', () => {
|
||||
expect(sanitizeProjectGitProviders({
|
||||
provider: 'bitbucket',
|
||||
github: { apiBaseUrl: 'github.example.com' },
|
||||
})).toEqual({ github: { apiBaseUrl: 'https://github.example.com' } });
|
||||
expect(sanitizeProjectGitProviders({ provider: '' })).toBeUndefined();
|
||||
expect(sanitizeProjectGitProviders({ provider: ' ' })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProjectProvider / getProjectProviderFromDirectory', () => {
|
||||
test('returns the forced provider or null', () => {
|
||||
fs.mkdirSync(PROJECTS_DIR, { recursive: true });
|
||||
fs.writeFileSync(projectFile('proj_provider'), JSON.stringify({
|
||||
gitProviders: { provider: 'gitea', gitea: { apiBaseUrl: 'https://gitea.example.com' } },
|
||||
}, null, 2));
|
||||
expect(getProjectProvider('proj_provider')).toBe('gitea');
|
||||
expect(getProjectProvider('proj_missing')).toBeNull();
|
||||
});
|
||||
|
||||
test('resolves the forced provider through the directory', () => {
|
||||
fs.mkdirSync(PROJECTS_DIR, { recursive: true });
|
||||
fs.writeFileSync(projectFile('proj_forced'), JSON.stringify({
|
||||
gitProviders: { provider: 'gitlab' },
|
||||
}, null, 2));
|
||||
writeSettingsProjects([{ id: 'proj_forced', path: '/home/user/gl' }]);
|
||||
expect(getProjectProviderFromDirectory('/home/user/gl')).toBe('gitlab');
|
||||
expect(getProjectProviderFromDirectory('/home/user/unregistered')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveProjectGitProviders round-trip', () => {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
- `packages/web/server/lib/gitea/routes.js`: Express route registration for `/api/gitea/*` endpoints.
|
||||
- `packages/web/server/lib/gitea/auth.js`: PAT auth storage, multi-account support, base URL normalization.
|
||||
- `packages/web/server/lib/gitea/client.js`: raw `fetch` Gitea REST v1 client (timeout, ETag conditional GET, rate-limit cooldown, `Link`-header pagination, redirect handling).
|
||||
- `packages/web/server/lib/gitea/client.d.ts`: hand-written type declaration for `client.js` (the module is plain JS); consumed by the live-test harness.
|
||||
- `packages/web/server/lib/gitea/repo.js`: Gitea remote URL parsing (flat `owner/repo`) and directory-to-repo resolution.
|
||||
- `packages/web/server/lib/opencode/feature-routes-runtime.js`: API route layer that calls this module (via `registerGiteaRoutes`).
|
||||
- `packages/web/src/api/gitea.ts`: web client wrapper for Gitea endpoints.
|
||||
@@ -48,7 +49,7 @@
|
||||
- Auth storage: `~/.config/openchamber/gitea-auth.json` (override with `OPENCHAMBER_DATA_DIR`).
|
||||
- Writes are atomic (tmp file + rename) and file mode is `0o600`.
|
||||
- Base URL resolution: the caller-supplied `baseUrl` (normalized) is the primary source, then the effective default (configured `settings.json` `gitProviders.gitea.apiBaseUrl`, else `https://codeberg.org`). Stored entries without a usable base URL are dropped.
|
||||
- Per-project overrides: a per-project `gitProviders.gitea.apiBaseUrl` override (stored under `projects/<projectId>.json`, resolved via `getEffectiveProviderApiBaseUrl('gitea', directory)` in `packages/web/server/lib/git-providers/project-config.js`) replaces the account's base URL for that project's data routes (`getGiteaClientOrNull(directory)`), and its host is accepted for directory-to-repo resolution (`resolveGiteaRepoFromDirectory`). Global routes (`auth/status`, `auth/connect`, `auth/activate`, DELETE auth, `me`, `repo/branches`) stay global.
|
||||
- Per-project overrides: a per-project `gitProviders.gitea.apiBaseUrl` override (stored under `projects/<projectId>.json`, resolved via `getEffectiveProviderApiBaseUrl('gitea', directory)` in `packages/web/server/lib/git-providers/project-config.js`) replaces the account's base URL for that project's data routes (`getGiteaClientOrNull(directory)`), and its host is accepted for directory-to-repo resolution (`resolveGiteaRepoFromDirectory`). A forced `gitProviders.provider: 'gitea'` accepts any remote host for directory resolution. Global routes (`auth/status`, `auth/connect`, `auth/activate`, DELETE auth, `me`, `repo/branches`) stay global.
|
||||
- Account id: `` `${host}:${username}` `` (e.g. `gitea.example.com:alice`), falling back to `token:<first8>` when the username is missing.
|
||||
- Auth header on every request: `Authorization: token <pat>`.
|
||||
- Gitea's `GET /user` uses `login`/`full_name`/`html_url`; `setGiteaAuth` accepts both that and the `username`/`web_url` variants.
|
||||
@@ -80,7 +81,7 @@
|
||||
- Commit statuses: `GET /repos/{owner}/{repo}/commits/{sha}/statuses?limit=100` (the `prs/statuses` route resolves the PR `head.sha` first, then maps statuses to `{ state, name, description, url, createdAt }` with `state` lowercased).
|
||||
- PR create: `POST /repos/{owner}/{repo}/pulls` with `{ title, head, base, body? }` (body omitted when absent).
|
||||
- PR update: `PATCH /repos/{owner}/{repo}/pulls/{number}` with `{ title?, body?, state? }` (undefined fields omitted; the PR number IS the issue index, so the edit-issue `state` transition applies directly).
|
||||
- PR merge: `POST /repos/{owner}/{repo}/pulls/{number}/merge` with `{ Do: true, MergeMethod: 'merge' | 'squash' | 'rebase' }` (`method` defaults to `'merge'`).
|
||||
- PR merge: `POST /repos/{owner}/{repo}/pulls/{number}/merge` with `{ Do: 'merge' | 'squash' | 'rebase' }` (`method` defaults to `'merge'`). `Do` is a string enum of the merge style — Gitea has no separate `MergeMethod` field.
|
||||
- Issue comment write: `POST /repos/{owner}/{repo}/issues/{number}/comments` with `{ body }` (PRs are issues at the API level, so `prs/comment` uses the same endpoint with the PR number as the index).
|
||||
- Issue update: `PATCH /repos/{owner}/{repo}/issues/{number}` with `{ title?, body?, state?, labels?, assignees?, milestone?, unset_milestone? }` (labels are label **names**, assignees are logins; `milestone` is resolved from a title to a milestone id and `null` sets `unset_milestone: true`).
|
||||
- Pull review write: `POST /repos/{owner}/{repo}/pulls/{number}/reviews` with `{ event, body? }` (`event` is `APPROVED`/`REQUEST_CHANGES`/`COMMENT`).
|
||||
@@ -131,6 +132,7 @@ Conventions mirror `github/routes.js` and `gitlab/routes.js`:
|
||||
|
||||
- `packages/web/src/api/gitea.ts` calls every `/api/gitea/*` endpoint and maps them to the shared types.
|
||||
- `packages/ui/src/lib/api/types.ts` defines the shared `Gitea*` response types used across web, desktop, VS Code, and mobile.
|
||||
- `packages/web/scripts/gitea-live-test.ts` is a live-test harness for the raw client: run with `bun run gitea:live-test` (requires `GITEA_TOKEN`; `GITEA_BASE_URL` defaults to `https://git.example.com`). It exercises every client method against a real instance, reports PASS/WARN/FAIL/SKIP per endpoint, and runs a controlled write pass (scratch issue plus a scratch-repo PR lifecycle that is deleted afterward).
|
||||
|
||||
## Failure handling
|
||||
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// Hand-written declaration for the plain-JS Gitea/Forgejo REST v1 client
|
||||
// (client.js). Kept in sync with the client's public surface; the web package
|
||||
// type-checks the gitea live-test harness which imports this module.
|
||||
|
||||
export interface GiteaClientPageInfo {
|
||||
page: number | null;
|
||||
next: string | null;
|
||||
total: number | null;
|
||||
hasMore: boolean;
|
||||
nextUrl?: string;
|
||||
}
|
||||
|
||||
export interface GiteaClientResponse {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
data: unknown;
|
||||
page: GiteaClientPageInfo | null;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type GiteaQuery = Record<string, string | number | boolean | null | undefined>;
|
||||
|
||||
export interface GiteaRequestOptions {
|
||||
method?: string;
|
||||
query?: GiteaQuery;
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
raw?: boolean;
|
||||
}
|
||||
|
||||
export interface GiteaClient {
|
||||
baseUrl: string;
|
||||
request: (path: string, options?: GiteaRequestOptions) => Promise<GiteaClientResponse>;
|
||||
user: () => Promise<GiteaClientResponse>;
|
||||
repo: (owner: string, repo: string) => Promise<GiteaClientResponse>;
|
||||
issues: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
issue: (owner: string, repo: string, number: number) => Promise<GiteaClientResponse>;
|
||||
issueComments: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
createIssueComment: (owner: string, repo: string, number: number, body: string) => Promise<GiteaClientResponse>;
|
||||
createIssue: (owner: string, repo: string, params: Record<string, unknown>) => Promise<GiteaClientResponse>;
|
||||
updateIssue: (owner: string, repo: string, number: number, params: Record<string, unknown>) => Promise<GiteaClientResponse>;
|
||||
milestones: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
repoLabels: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
pullRequests: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
pullRequest: (owner: string, repo: string, number: number) => Promise<GiteaClientResponse>;
|
||||
pullRequestDiff: (owner: string, repo: string, number: number) => Promise<GiteaClientResponse>;
|
||||
pullRequestFiles: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
pullRequestCommits: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
pullRequestReviews: (owner: string, repo: string, number: number, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
createPullReview: (owner: string, repo: string, number: number, params: Record<string, unknown>) => Promise<GiteaClientResponse>;
|
||||
commitStatuses: (owner: string, repo: string, sha: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
createPullRequest: (owner: string, repo: string, body: Record<string, unknown>) => Promise<GiteaClientResponse>;
|
||||
updatePullRequest: (owner: string, repo: string, number: number, body: Record<string, unknown>) => Promise<GiteaClientResponse>;
|
||||
mergePullRequest: (owner: string, repo: string, number: number, body: Record<string, unknown>) => Promise<GiteaClientResponse>;
|
||||
branches: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
assignees: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
tags: (owner: string, repo: string, params?: GiteaQuery) => Promise<GiteaClientResponse>;
|
||||
}
|
||||
|
||||
export function createGiteaClient(options: { token: string; baseUrl: string }): GiteaClient;
|
||||
export function getGiteaClientOrNull(directory?: string): GiteaClient | null;
|
||||
export function isGiteaRateLimited(): boolean;
|
||||
export function noteGiteaRateLimit(error: unknown): void;
|
||||
@@ -242,17 +242,17 @@ describe('pull request write methods', () => {
|
||||
expect(JSON.parse(options.body)).toEqual({ title: 'Updated', body: 'Body text' });
|
||||
});
|
||||
|
||||
test('mergePullRequest POSTs Do and MergeMethod to the merge endpoint', async () => {
|
||||
test('mergePullRequest POSTs the merge style in Do to the merge endpoint', async () => {
|
||||
const fetchMock = vi.fn(async () => jsonResponse({ merged: true }));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
const client = createGiteaClient({ token: 't', baseUrl: 'https://gitea.example.com' });
|
||||
await client.mergePullRequest('owner', 'repo', 5, { Do: true, MergeMethod: 'squash' });
|
||||
await client.mergePullRequest('owner', 'repo', 5, { Do: 'squash' });
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[0];
|
||||
expect(String(url)).toBe('https://gitea.example.com/api/v1/repos/owner/repo/pulls/5/merge');
|
||||
expect(options.method).toBe('POST');
|
||||
expect(JSON.parse(options.body)).toEqual({ Do: true, MergeMethod: 'squash' });
|
||||
expect(JSON.parse(options.body)).toEqual({ Do: 'squash' });
|
||||
});
|
||||
|
||||
test('write methods surface error statuses without throwing', async () => {
|
||||
@@ -260,7 +260,7 @@ describe('pull request write methods', () => {
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
const client = createGiteaClient({ token: 't', baseUrl: 'https://gitea.example.com' });
|
||||
const result = await client.mergePullRequest('owner', 'repo', 5, { Do: true, MergeMethod: 'merge' });
|
||||
const result = await client.mergePullRequest('owner', 'repo', 5, { Do: 'merge' });
|
||||
expect(result.status).toBe(409);
|
||||
expect(result.data).toEqual({ message: 'Conflict' });
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getRemoteUrl } from '../git/index.js';
|
||||
import { getGiteaAuthAccounts, normalizeBaseUrl } from './auth.js';
|
||||
import { getEffectiveProviderApiBaseUrl } from '../git-providers/project-config.js';
|
||||
import { getEffectiveProviderApiBaseUrl, getProjectProviderFromDirectory } from '../git-providers/project-config.js';
|
||||
|
||||
// When no explicit host allowlist is provided, accept any host that matches the
|
||||
// base URL of a stored Gitea account. Gitea/Forgejo is self-hosted, so there is
|
||||
@@ -50,7 +50,7 @@ function acceptedHosts(knownHosts) {
|
||||
* When omitted, hosts from stored auth accounts are accepted. `github.com` and
|
||||
* `gitlab.com` are never accepted.
|
||||
*/
|
||||
export const parseGiteaRemoteUrl = (raw, knownHosts) => {
|
||||
export const parseGiteaRemoteUrl = (raw, knownHosts, options = {}) => {
|
||||
if (typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export const parseGiteaRemoteUrl = (raw, knownHosts) => {
|
||||
if (host === 'github.com' || host === 'gitlab.com') {
|
||||
return null;
|
||||
}
|
||||
if (!acceptedHosts(knownHosts).has(host)) {
|
||||
if (!options.allowAnyHost && !acceptedHosts(knownHosts).has(host)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -133,8 +133,10 @@ export async function resolveGiteaRepoFromDirectory(directory, remoteName = 'ori
|
||||
// ignore a malformed override base URL
|
||||
}
|
||||
}
|
||||
// A forced gitea provider (per-project override) accepts any remote host.
|
||||
const forcedProvider = getProjectProviderFromDirectory(directory);
|
||||
return {
|
||||
repo: parseGiteaRemoteUrl(remoteUrl, knownHosts),
|
||||
repo: parseGiteaRemoteUrl(remoteUrl, knownHosts, { allowAnyHost: forcedProvider === 'gitea' }),
|
||||
remoteUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,6 +22,12 @@ vi.mock('../git-providers/project-config.js', async (importOriginal) => {
|
||||
}
|
||||
return actual.getEffectiveProviderApiBaseUrl(provider, directory);
|
||||
}),
|
||||
getProjectProviderFromDirectory: vi.fn((directory) => {
|
||||
if (directory === '/forced/project') {
|
||||
return 'gitea';
|
||||
}
|
||||
return actual.getProjectProviderFromDirectory(directory);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -150,4 +156,11 @@ describe('resolveGiteaRepoFromDirectory', () => {
|
||||
const { repo } = await resolveGiteaRepoFromDirectory('/some/project');
|
||||
expect(repo).toBeNull();
|
||||
});
|
||||
|
||||
test('accepts any remote host when the provider is forced to gitea', async () => {
|
||||
vi.mocked(getRemoteUrl).mockResolvedValue('git@gitea.internal.corp:team/app.git');
|
||||
const { repo, remoteUrl } = await resolveGiteaRepoFromDirectory('/forced/project');
|
||||
expect(remoteUrl).toBe('git@gitea.internal.corp:team/app.git');
|
||||
expect(repo).toMatchObject({ owner: 'team', repo: 'app', host: 'gitea.internal.corp' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1225,7 +1225,10 @@ export function registerGiteaRoutes(app, options = {}) {
|
||||
return res.status(400).json({ error: 'Unable to resolve Gitea repo from directory' });
|
||||
}
|
||||
|
||||
const body = { Do: true, MergeMethod: method };
|
||||
// Gitea's merge endpoint takes the merge style directly in `Do` (a
|
||||
// string enum: merge/rebase/rebase-merge/squash/fast-forward-only/
|
||||
// manually-merged). There is no separate `MergeMethod` field.
|
||||
const body = { Do: method };
|
||||
|
||||
const resp = await withTimeout(client.mergePullRequest(owner, repo, number, body), ROUTE_TIMEOUT_MS, 'gitea pr merge');
|
||||
if (resp.status === 429) {
|
||||
|
||||
@@ -889,7 +889,7 @@ describe('Gitea data routes', () => {
|
||||
expect(response.body).toEqual({ error: 'Pull request not found' });
|
||||
});
|
||||
|
||||
test('pr/merge POSTs Do/MergeMethod and reports merged:true', async () => {
|
||||
test('pr/merge POSTs the merge style in Do and reports merged:true', async () => {
|
||||
const fetchMock = scriptedFetch([
|
||||
(url, options) => {
|
||||
if (matches(/\/pulls\/12\/merge$/)(url) && options.method === 'POST') {
|
||||
@@ -908,10 +908,10 @@ describe('Gitea data routes', () => {
|
||||
expect(response.body).toEqual({ connected: true, merged: true });
|
||||
const [, options] = fetchMock.mock.calls[0];
|
||||
expect(options.method).toBe('POST');
|
||||
expect(JSON.parse(options.body)).toEqual({ Do: true, MergeMethod: 'merge' });
|
||||
expect(JSON.parse(options.body)).toEqual({ Do: 'merge' });
|
||||
});
|
||||
|
||||
test('pr/merge maps the method to MergeMethod', async () => {
|
||||
test('pr/merge maps the method to Do', async () => {
|
||||
const fetchMock = scriptedFetch([
|
||||
(url, options) => {
|
||||
if (matches(/\/pulls\/12\/merge$/)(url) && options.method === 'POST') {
|
||||
@@ -927,7 +927,7 @@ describe('Gitea data routes', () => {
|
||||
.send({ directory: '/tmp/work', number: 12, method: 'squash' });
|
||||
|
||||
const [, options] = fetchMock.mock.calls[0];
|
||||
expect(JSON.parse(options.body)).toEqual({ Do: true, MergeMethod: 'squash' });
|
||||
expect(JSON.parse(options.body)).toEqual({ Do: 'squash' });
|
||||
});
|
||||
|
||||
test('pr/merge passes through a Gitea merge rejection as merged:false', async () => {
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
- Auth storage: `~/.config/openchamber/gitlab-auth.json` (override with `OPENCHAMBER_DATA_DIR`).
|
||||
- Writes are atomic (tmp file + rename) and file mode is `0o600`.
|
||||
- Base URL resolution: caller-supplied `baseUrl` (normalized) -> effective default via `getGitLabDefaultBaseUrl()` (configured `settings.json` `gitProviders.gitlab.apiBaseUrl`, else `https://gitlab.com`).
|
||||
- Per-project overrides: data routes resolve a directory-scoped API base via `getEffectiveProviderApiBaseUrl('gitlab', directory)` (in `packages/web/server/lib/git-providers/project-config.js`). A per-project `gitProviders.gitlab.apiBaseUrl` override (stored under `projects/<projectId>.json`) replaces the global default for that project's routes, and its host is accepted for directory-to-repo resolution (`resolveGitLabRepoFromDirectory`); a connected account whose host matches the remote keeps its own base URL. Global routes (`auth/connect`, `auth/status`, `auth/activate`, `me`, `repo/branches`) stay global.
|
||||
- Per-project overrides: data routes resolve a directory-scoped API base via `getEffectiveProviderApiBaseUrl('gitlab', directory)` (in `packages/web/server/lib/git-providers/project-config.js`). A per-project `gitProviders.gitlab.apiBaseUrl` override (stored under `projects/<projectId>.json`) replaces the global default for that project's routes, and its host is accepted for directory-to-repo resolution (`resolveGitLabRepoFromDirectory`); a connected account whose host matches the remote keeps its own base URL. A forced `gitProviders.provider: 'gitlab'` accepts any remote host for directory resolution. Global routes (`auth/connect`, `auth/status`, `auth/activate`, `me`, `repo/branches`) stay global.
|
||||
- Account id: `` `${host}:${username}` `` (e.g. `gitlab.com:alice`), falling back to `token:<first8>` when the username is missing.
|
||||
- Auth header on every request: `PRIVATE-TOKEN: <pat>`.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getRemoteUrl } from '../git/index.js';
|
||||
import { getGitLabAuthAccounts, normalizeBaseUrl } from './auth.js';
|
||||
import { getEffectiveProviderApiBaseUrl } from '../git-providers/project-config.js';
|
||||
import { getEffectiveProviderApiBaseUrl, getProjectProviderFromDirectory } from '../git-providers/project-config.js';
|
||||
|
||||
// When no explicit host allowlist is provided, accept gitlab.com or any host
|
||||
// that matches the base URL of a stored GitLab account. Never github.com.
|
||||
@@ -49,7 +49,7 @@ function acceptedHosts(knownHosts) {
|
||||
* When omitted, `gitlab.com` and hosts from stored auth accounts are accepted.
|
||||
* github.com is never accepted.
|
||||
*/
|
||||
export const parseGitLabRemoteUrl = (raw, knownHosts) => {
|
||||
export const parseGitLabRemoteUrl = (raw, knownHosts, options = {}) => {
|
||||
if (typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
@@ -84,7 +84,7 @@ export const parseGitLabRemoteUrl = (raw, knownHosts) => {
|
||||
if (host === 'github.com') {
|
||||
return null;
|
||||
}
|
||||
if (!acceptedHosts(knownHosts).has(host)) {
|
||||
if (!options.allowAnyHost && !acceptedHosts(knownHosts).has(host)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -131,8 +131,10 @@ export async function resolveGitLabRepoFromDirectory(directory, remoteName = 'or
|
||||
// ignore a malformed override base URL
|
||||
}
|
||||
}
|
||||
// A forced gitlab provider (per-project override) accepts any remote host.
|
||||
const forcedProvider = getProjectProviderFromDirectory(directory);
|
||||
return {
|
||||
repo: parseGitLabRemoteUrl(remoteUrl, knownHosts),
|
||||
repo: parseGitLabRemoteUrl(remoteUrl, knownHosts, { allowAnyHost: forcedProvider === 'gitlab' }),
|
||||
remoteUrl,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,6 +22,12 @@ vi.mock('../git-providers/project-config.js', async (importOriginal) => {
|
||||
}
|
||||
return actual.getEffectiveProviderApiBaseUrl(provider, directory);
|
||||
}),
|
||||
getProjectProviderFromDirectory: vi.fn((directory) => {
|
||||
if (directory === '/forced/project') {
|
||||
return 'gitlab';
|
||||
}
|
||||
return actual.getProjectProviderFromDirectory(directory);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -147,4 +153,11 @@ describe('resolveGitLabRepoFromDirectory', () => {
|
||||
const { repo } = await resolveGitLabRepoFromDirectory('/some/project');
|
||||
expect(repo).toBeNull();
|
||||
});
|
||||
|
||||
test('accepts any remote host when the provider is forced to gitlab', async () => {
|
||||
vi.mocked(getRemoteUrl).mockResolvedValue('git@gitlab.internal.corp:team/app.git');
|
||||
const { repo, remoteUrl } = await resolveGitLabRepoFromDirectory('/forced/project');
|
||||
expect(remoteUrl).toBe('git@gitlab.internal.corp:team/app.git');
|
||||
expect(repo).toMatchObject({ namespace: 'team', project: 'app', host: 'gitlab.internal.corp' });
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user