ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(connections): one-click GitHub setup via the GitHub App manifest flow
Juan Denis5fc0b881b402
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a370fb1..0d01b81c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,18 @@ awaiting a stable release:### Added+- **One-click GitHub setup (GitHub App manifest flow)** — connecting GitHub no+ longer means hand-registering an OAuth app and pasting a client id + secret.+ An admin clicks **Set up in one click** in Settings → Connections; ServerKit+ hands GitHub an app *manifest*, the admin confirms once on github.com, and+ GitHub returns freshly-minted credentials that are stored **locally on the+ server** (client id/secret in settings, private key encrypted) — nothing+ secret ships in the open-source build. Setup then chains straight into the+ app's install screen, which grants repo access and authorizes in one hop. The+ connect flow routes through the app install URL, and repositories are listed+ per-installation (GitHub Apps don't use `/user/repos`). Bringing your own+ OAuth app still works, tucked under an "Advanced" disclosure. New endpoints:+ `GET/POST /api/v1/source-connections/admin/github/app-manifest[/complete]`.- **New Service is a real three-step wizard, and Templates is one catalog** —`/services/new` was a form-wall that rendered everything at once (a "Ready toImport" rail of placeholder rows, a decorative Connect→Detect→Deploy strip,diff --git a/backend/app/api/source_connections.py b/backend/app/api/source_connections.pyindex 347162b1..a02eb1b3 100644--- a/backend/app/api/source_connections.py+++ b/backend/app/api/source_connections.py@@ -132,6 +132,39 @@ def update_github_admin_config():return jsonify(result), 200+@source_connections_bp.route('/admin/github/app-manifest', methods=['GET'])+@admin_required+def github_app_manifest():+ """Build the GitHub App manifest for the one-click setup flow."""+ redirect_uri = request.args.get('redirect_uri', '')+ base_url = request.args.get('base_url', '') or request.host_url+ try:+ manifest, state, post_url = SourceConnectionService.build_github_app_manifest(+ redirect_uri, base_url)+ return jsonify({'manifest': manifest, 'state': state, 'post_url': post_url}), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+++@source_connections_bp.route('/admin/github/app-manifest/complete', methods=['POST'])+@admin_required+def complete_github_app_manifest():+ """Convert the manifest code GitHub returned into a stored GitHub App."""+ user = User.query.get(get_jwt_identity())+ data = request.get_json() or {}+ try:+ result = SourceConnectionService.complete_github_app_manifest(+ code=data.get('code', ''),+ state=data.get('state', ''),+ user_id=user.id if user else None,+ )+ return jsonify(result), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+ except HTTPError as exc:+ return jsonify({'error': _github_error(exc)}), 400++def _github_error(exc):response = getattr(exc, 'response', None)if response is None:diff --git a/backend/app/services/source_connection_service.py b/backend/app/services/source_connection_service.pyindex 78c16ef5..4cf3822a 100644--- a/backend/app/services/source_connection_service.py+++ b/backend/app/services/source_connection_service.py@@ -22,6 +22,7 @@ class SourceConnectionService:GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize'GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token'GITHUB_API_URL = 'https://api.github.com'+ GITHUB_APP_NEW_URL = 'https://github.com/settings/apps/new'GITHUB_SCOPES = ['repo', 'read:user', 'user:email']GITLAB_AUTHORIZE_URL = 'https://gitlab.com/oauth/authorize'@@ -45,11 +46,21 @@ class SourceConnectionService:if redacted and client_secret:client_secret = f'****{client_secret[-4:]}'+ # When GitHub was set up via the one-click GitHub App manifest flow, we+ # also track the app slug so the UI can show it and the connect flow can+ # route through the app's install URL. `provider_kind` is 'app' for a+ # manifest-provisioned GitHub App, 'oauth' for a hand-entered OAuth app.+ app_slug = SettingsService.get('source_github_app_slug', '') or ''return {'client_id': client_id,'client_secret': client_secret,'configured': bool(client_id and client_secret),'scopes': cls.GITHUB_SCOPES,+ 'provider_kind': 'app' if app_slug else 'oauth',+ 'app_slug': app_slug,+ 'app_name': SettingsService.get('source_github_app_name', '') or '',+ 'app_html_url': SettingsService.get('source_github_app_html_url', '') or '',+ 'install_url': f'https://github.com/apps/{app_slug}/installations/new' if app_slug else '',}@classmethod@@ -65,6 +76,108 @@ class SourceConnectionService:updated.append('client_secret')return {'updated': updated, 'config': cls.get_github_config(redacted=True)}+ # ==================================================================+ # One-click GitHub App setup (manifest flow)+ # ------------------------------------------------------------------+ # An open-source, self-hosted panel can't ship a client secret, and asking+ # every operator to hand-register an OAuth app and copy two secrets is+ # friction. GitHub's app-manifest flow lets each instance create its OWN+ # GitHub App in a couple of clicks: we hand GitHub a manifest, the operator+ # confirms on github.com, and GitHub hands back freshly-minted credentials+ # that we store locally. No shared secret, no infra on our side.+ # ==================================================================++ @classmethod+ def build_github_app_manifest(cls, redirect_uri, base_url):+ """Return ``(manifest, state, post_url)`` for the GitHub App manifest flow.++ The frontend POSTs ``manifest`` (JSON) to ``post_url?state=<state>``; the+ operator confirms on github.com; GitHub redirects to ``redirect_uri`` with+ ``?code=&state=`` which :meth:`complete_github_app_manifest` converts into+ stored credentials.+ """+ if not redirect_uri or not base_url:+ raise ValueError('redirect_uri and base_url are required')++ base_url = base_url.rstrip('/')+ state = secrets.token_urlsafe(32)+ session['source_github_app_state'] = state++ # App names are globally unique on GitHub; a short random suffix avoids+ # collisions between instances/re-runs.+ suffix = secrets.token_hex(3)+ manifest = {+ 'name': f'ServerKit {suffix}',+ 'url': base_url,+ 'redirect_url': redirect_uri,+ # Where GitHub sends the user after they install the app (also the+ # user-to-server OAuth callback, so install + authorize land here).+ 'callback_urls': [f'{base_url}/connections/callback/github'],+ 'setup_url': f'{base_url}/connections/callback/github',+ 'setup_on_update': False,+ 'public': False,+ 'default_permissions': {+ 'contents': 'read',+ 'metadata': 'read',+ 'pull_requests': 'read',+ },+ 'default_events': ['push', 'pull_request'],+ # Issue a user-to-server token as part of installation so the connect+ # step is a single hop (install + authorize together).+ 'request_oauth_on_install': True,+ }+ return manifest, state, cls.GITHUB_APP_NEW_URL++ @classmethod+ def complete_github_app_manifest(cls, code, state, user_id=None):+ """Convert a manifest ``code`` into a GitHub App and persist its+ credentials. Returns a small summary incl. the install URL."""+ expected_state = session.pop('source_github_app_state', None)+ if not expected_state or state != expected_state:+ raise ValueError('Invalid GitHub App manifest state')+ if not code:+ raise ValueError('Missing manifest code')++ response = requests.post(+ f'{cls.GITHUB_API_URL}/app-manifests/{quote(code)}/conversions',+ headers={'Accept': 'application/vnd.github+json'},+ timeout=15,+ )+ response.raise_for_status()+ data = response.json()++ client_id = data.get('client_id')+ client_secret = data.get('client_secret')+ slug = data.get('slug')+ if not (client_id and client_secret and slug):+ raise ValueError('GitHub did not return complete app credentials')++ SettingsService.set('source_github_client_id', client_id, user_id=user_id)+ SettingsService.set('source_github_client_secret', client_secret, user_id=user_id)+ SettingsService.set('source_github_app_id', str(data.get('id') or ''), user_id=user_id)+ SettingsService.set('source_github_app_slug', slug, user_id=user_id)+ SettingsService.set('source_github_app_name', data.get('name') or '', user_id=user_id)+ SettingsService.set('source_github_app_html_url', data.get('html_url') or '', user_id=user_id)+ # The private key and webhook secret are sensitive — store encrypted.+ if data.get('pem'):+ SettingsService.set('source_github_app_pem', encrypt_secret(data['pem']), user_id=user_id)+ if data.get('webhook_secret'):+ SettingsService.set(+ 'source_github_app_webhook_secret',+ encrypt_secret(data['webhook_secret']), user_id=user_id,+ )++ return {+ 'slug': slug,+ 'name': data.get('name') or slug,+ 'html_url': data.get('html_url') or '',+ 'install_url': f'https://github.com/apps/{slug}/installations/new',+ }++ @classmethod+ def _github_app_slug(cls):+ return SettingsService.get('source_github_app_slug', '') or ''+@classmethoddef generate_github_authorize_url(cls, redirect_uri):config = cls.get_github_config()@@ -74,6 +187,14 @@ class SourceConnectionService:state = secrets.token_urlsafe(32)session['source_github_state'] = state+ # GitHub App: send the user to the install screen (with OAuth-on-install+ # this grants repo access AND returns an authorization code to our+ # callback in one hop). Classic OAuth app: the plain authorize screen.+ slug = cls._github_app_slug()+ if slug:+ params = {'state': state}+ return f'https://github.com/apps/{slug}/installations/new?{urlencode(params)}', state+params = {'client_id': config['client_id'],'redirect_uri': redirect_uri,@@ -151,18 +272,45 @@ class SourceConnectionService:db.session.delete(connection)db.session.commit()+ @classmethod+ def _list_github_app_repos(cls, token):+ """List repositories a GitHub App user-to-server token can reach, across+ every installation the user has granted. (GitHub Apps don't use+ ``/user/repos`` — repo access is per-installation.)"""+ repos = []+ installations = cls._github_get(token, '/user/installations?per_page=100')+ items = installations.get('installations', []) if isinstance(installations, dict) else []+ for installation in items:+ inst_id = installation.get('id')+ if not inst_id:+ continue+ page = 1+ while True:+ data = cls._github_get(+ token, f'/user/installations/{inst_id}/repositories?per_page=100&page={page}')+ batch = data.get('repositories', []) if isinstance(data, dict) else []+ repos.extend(batch)+ if len(batch) < 100:+ break+ page += 1+ return repos+@classmethoddef list_github_repositories(cls, user_id, search='', page=1, per_page=50):token = cls._get_github_token(user_id)- params = {- 'visibility': 'all',- 'affiliation': 'owner,collaborator,organization_member',- 'sort': 'updated',- 'direction': 'desc',- 'page': max(int(page or 1), 1),- 'per_page': min(max(int(per_page or 50), 1), 100),- }- repos = cls._github_get(token, f'/user/repos?{urlencode(params)}')+ if cls._github_app_slug():+ repos = cls._list_github_app_repos(token)+ repos.sort(key=lambda r: r.get('updated_at') or '', reverse=True)+ else:+ params = {+ 'visibility': 'all',+ 'affiliation': 'owner,collaborator,organization_member',+ 'sort': 'updated',+ 'direction': 'desc',+ 'page': max(int(page or 1), 1),+ 'per_page': min(max(int(per_page or 50), 1), 100),+ }+ repos = cls._github_get(token, f'/user/repos?{urlencode(params)}')search_text = (search or '').strip().lower()if search_text:repos = [diff --git a/backend/tests/BASELINE_COUNT b/backend/tests/BASELINE_COUNTindex ff7f50a6..f59ab94e 100644--- a/backend/tests/BASELINE_COUNT+++ b/backend/tests/BASELINE_COUNT@@ -1 +1 @@-2498+2505diff --git a/backend/tests/test_github_app_manifest.py b/backend/tests/test_github_app_manifest.pynew file mode 100644index 00000000..11610c8c--- /dev/null+++ b/backend/tests/test_github_app_manifest.py@@ -0,0 +1,130 @@+"""Proving tests for the one-click GitHub App manifest setup flow.++Covers the pure/mockable half of the flow: building the manifest, converting the+returned code into stored credentials, routing the connect URL through the app's+install screen when an app slug exists, surfacing app info in the config, and+listing repositories via installations in app mode. The live github.com+round-trip (create app → install → authorize) is verified manually.+"""+import flask+import pytest++from app.services.settings_service import SettingsService+from app.services.source_connection_service import SourceConnectionService as SC+++def test_build_manifest_shape_and_state(app):+ with app.test_request_context():+ manifest, state, post_url = SC.build_github_app_manifest(+ 'https://panel.example/connections/github-app/callback',+ 'https://panel.example',+ )+ assert post_url == SC.GITHUB_APP_NEW_URL+ assert manifest['name'].startswith('ServerKit')+ assert manifest['url'] == 'https://panel.example'+ assert manifest['redirect_url'].endswith('/connections/github-app/callback')+ assert manifest['callback_urls'] == ['https://panel.example/connections/callback/github']+ assert manifest['default_permissions']['contents'] == 'read'+ assert manifest['request_oauth_on_install'] is True+ assert manifest['public'] is False+ # State is remembered for the conversion step.+ assert flask.session['source_github_app_state'] == state+++def test_build_manifest_requires_urls(app):+ with app.test_request_context():+ with pytest.raises(ValueError):+ SC.build_github_app_manifest('', 'https://panel.example')+++def _fake_conversion_response():+ class FakeResp:+ def raise_for_status(self):+ return None++ def json(self):+ return {+ 'id': 424242,+ 'slug': 'serverkit-abc123',+ 'name': 'ServerKit abc123',+ 'client_id': 'Iv1.deadbeef',+ 'client_secret': 'super-secret',+ 'pem': '-----BEGIN RSA PRIVATE KEY-----\nkey\n-----END RSA PRIVATE KEY-----',+ 'webhook_secret': 'wh-secret',+ 'html_url': 'https://github.com/apps/serverkit-abc123',+ }+ return FakeResp()+++def test_complete_manifest_stores_credentials(app, monkeypatch):+ from app.services import source_connection_service as mod+ monkeypatch.setattr(mod.requests, 'post', lambda *a, **k: _fake_conversion_response())++ with app.test_request_context():+ flask.session['source_github_app_state'] = 'state-xyz'+ result = SC.complete_github_app_manifest('code-123', 'state-xyz', user_id=None)++ assert result['slug'] == 'serverkit-abc123'+ assert result['install_url'] == 'https://github.com/apps/serverkit-abc123/installations/new'++ cfg = SC.get_github_config()+ assert cfg['configured'] is True+ assert cfg['provider_kind'] == 'app'+ assert cfg['app_slug'] == 'serverkit-abc123'+ assert cfg['install_url'].endswith('/installations/new')+ # The raw client id is stored; the PEM is stored encrypted (not plaintext).+ assert SettingsService.get('source_github_client_id') == 'Iv1.deadbeef'+ pem = SettingsService.get('source_github_app_pem') or ''+ assert pem and 'BEGIN RSA PRIVATE KEY' not in pem+++def test_complete_manifest_rejects_bad_state(app):+ with app.test_request_context():+ flask.session['source_github_app_state'] = 'good'+ with pytest.raises(ValueError):+ SC.complete_github_app_manifest('code', 'bad', user_id=None)+++def test_authorize_url_uses_install_when_app(app):+ with app.test_request_context():+ SettingsService.set('source_github_client_id', 'cid')+ SettingsService.set('source_github_client_secret', 'sec')+ SettingsService.set('source_github_app_slug', 'serverkit-abc123')+ url, state = SC.generate_github_authorize_url('https://panel.example/cb')+ assert 'apps/serverkit-abc123/installations/new' in url+ assert f'state={state}' in url+++def test_authorize_url_classic_without_app(app):+ with app.test_request_context():+ SettingsService.set('source_github_client_id', 'cid')+ SettingsService.set('source_github_client_secret', 'sec')+ # No app slug -> classic OAuth authorize screen.+ url, _ = SC.generate_github_authorize_url('https://panel.example/cb')+ assert 'login/oauth/authorize' in url+ assert 'client_id=cid' in url+++def test_list_repositories_app_mode_uses_installations(app, monkeypatch):+ monkeypatch.setattr(SC, '_get_github_token', classmethod(lambda cls, uid: 'tok'))++ def fake_get(cls, token, path):+ if path.startswith('/user/installations?'):+ return {'installations': [{'id': 1}, {'id': 2}]}+ if '/installations/1/repositories' in path:+ return {'repositories': [+ {'id': 10, 'name': 'alpha', 'full_name': 'me/alpha', 'updated_at': '2024-02-01'},+ ]}+ if '/installations/2/repositories' in path:+ return {'repositories': [+ {'id': 20, 'name': 'beta', 'full_name': 'me/beta', 'updated_at': '2024-03-01'},+ ]}+ return []++ monkeypatch.setattr(SC, '_github_get', classmethod(fake_get))++ with app.test_request_context():+ SettingsService.set('source_github_app_slug', 'serverkit-abc123')+ repos = SC.list_github_repositories(user_id=1)+ names = [r['full_name'] for r in repos]+ assert names == ['me/beta', 'me/alpha'] # sorted by updated_at descdiff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 572a95fc..67bef455 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -49,6 +49,7 @@ import Downloads from './pages/Downloads';import SSLCertificates from './pages/SSLCertificates';import SSOCallback from './pages/SSOCallback';import SourceConnectionCallback from './pages/SourceConnectionCallback';+import GithubAppCallback from './pages/GithubAppCallback';import DatabaseMigration from './pages/DatabaseMigration';import ServerTemplates from './pages/ServerTemplates';import Workspaces from './pages/Workspaces';@@ -106,6 +107,7 @@ const PAGE_TITLES = {'/terminal': 'Terminal','/settings': 'Settings','/connections/callback/github': 'GitHub Connection',+ '/connections/github-app/callback': 'GitHub Setup','/migrate': 'Database Migration','/fleet': 'Agent Fleet','/fleet-monitor': 'Fleet Monitor',@@ -276,6 +278,11 @@ function AppRoutes() {<SourceConnectionCallback /></PrivateRoute>} />+ <Route path="/connections/github-app/callback" element={+ <PrivateRoute>+ <GithubAppCallback />+ </PrivateRoute>+ } /><Route path="/status/:slug" element={<PublicStatusPage />} />{/* Standalone plugin layouts — bare or custom. Each group isa sibling top-level Route under PrivateRoute, so thediff --git a/frontend/src/components/settings/connections/ConnectProviderModal.jsx b/frontend/src/components/settings/connections/ConnectProviderModal.jsxindex dd53262e..2da4bb47 100644--- a/frontend/src/components/settings/connections/ConnectProviderModal.jsx+++ b/frontend/src/components/settings/connections/ConnectProviderModal.jsx@@ -10,7 +10,7 @@import { useState } from 'react';import {CheckCircle2, ExternalLink, KeyRound, Link2, Mail, PlugZap, Server, Globe,- HardDrive, ShieldCheck, ShieldAlert, Trash2, Activity, ChevronDown, Boxes,+ HardDrive, ShieldCheck, ShieldAlert, Trash2, Activity, ChevronDown, Boxes, Zap,} from 'lucide-react';import { Link } from 'react-router-dom';import {@@ -27,7 +27,7 @@ import DnsActivity from './DnsActivity';export default function ConnectProviderModal({provider, open, onOpenChange, isAdmin,sourceStatus, sourceConfig, dnsProviders, cloudProviders, storageConfig, registrarConnections, containerRegistries, relayConfig,- onConnectSource, onDisconnectSource, onSaveSourceConfig,+ onConnectSource, onDisconnectSource, onSaveSourceConfig, onSetupGithubApp,onAddDns, onRemoveDns, onTestDns,onAddCloud, onRemoveCloud,onSaveStorage, onTestStorage,@@ -58,6 +58,7 @@ export default function ConnectProviderModal({onConnect={() => onConnectSource(provider)}onDisconnect={() => onDisconnectSource(provider)}onSaveConfig={(cfg) => onSaveSourceConfig(provider, cfg)}+ onSetupApp={onSetupGithubApp}/>)}@@ -113,12 +114,17 @@ export default function ConnectProviderModal({);}-// ── Source: GitHub / GitLab ──-function SourceBody({ provider, status, config, isAdmin, onConnect, onDisconnect, onSaveConfig }) {+// ── Source: GitHub / GitLab / Bitbucket ──+function SourceBody({ provider, status, config, isAdmin, onConnect, onDisconnect, onSaveConfig, onSetupApp }) {const connection = status?.connection;const configured = status?.configured;+ const isGithub = provider.provider === 'github';+ const appSlug = config?.app_slug || '';const callbackUrl = `${window.location.origin}/connections/callback/${provider.provider}`;const [cfg, setCfg] = useState({ client_id: config?.client_id || '', client_secret: config?.client_secret || '' });+ // GitHub leads with the one-click app; the manual OAuth form is tucked under+ // "Advanced". Other providers keep the manual form open.+ const [advancedOpen, setAdvancedOpen] = useState(!isGithub);const [busy, setBusy] = useState(false);async function save(e) {@@ -144,10 +150,12 @@ function SourceBody({ provider, status, config, isAdmin, onConnect, onDisconnect<div className="conn-empty"><span className="conn-empty__icon"><Link2 size={18} /></span><div className="conn-empty__text">- <strong>{configured ? `Connect your ${provider.name} account` : `${provider.name} OAuth is not configured yet`}</strong>+ <strong>{configured ? `Connect your ${provider.name} account` : `${provider.name} is not set up yet`}</strong><span>{configured? 'Authorize ServerKit once, then pick repositories directly on the New Service page.'- : 'An admin needs to add an OAuth app below before anyone can connect.'}</span>+ : isGithub+ ? 'Set it up in one click below — no copying secrets — then connect your account.'+ : 'An admin needs to add an OAuth app below before anyone can connect.'}</span></div><Button type="button" size="sm" disabled={!configured || busy} onClick={onConnect}><PlugZap size={15} /> Connect {provider.name}@@ -155,31 +163,72 @@ function SourceBody({ provider, status, config, isAdmin, onConnect, onDisconnect</div>)}- {isAdmin && (- <form className="conn-form" onSubmit={save}>- <div className="conn-form__heading"><KeyRound size={15} /> OAuth app credentials</div>- <div className="conn-form__grid">- <div className="form-group">- <Label htmlFor="src-client-id">Client ID</Label>- <Input id="src-client-id" value={cfg.client_id} onChange={(e) => setCfg((c) => ({ ...c, client_id: e.target.value }))} placeholder={`${provider.name} OAuth client ID`} autoComplete="off" />- </div>- <div className="form-group">- <Label htmlFor="src-client-secret">Client Secret</Label>- <Input id="src-client-secret" type="password" value={cfg.client_secret} onChange={(e) => setCfg((c) => ({ ...c, client_secret: e.target.value }))} placeholder={`${provider.name} OAuth client secret`} autoComplete="off" />+ {/* One-click GitHub App setup (admin, GitHub only). */}+ {isAdmin && isGithub && (+ <div className="conn-oneclick">+ <div className="conn-oneclick__head"><Zap size={15} /> One-click setup</div>+ <p className="conn-oneclick__blurb">+ Create a dedicated GitHub App for this server. You confirm once on GitHub —+ no OAuth secrets to copy — and its credentials are stored locally on your server.+ </p>+ {appSlug && (+ <div className="conn-oneclick__done">+ <CheckCircle2 size={14} /> App <strong>{config.app_name || appSlug}</strong> is set up.+ {config.app_html_url && (+ <a href={config.app_html_url} target="_blank" rel="noreferrer">+ <ExternalLink size={12} /> Manage on GitHub+ </a>+ )}</div>- </div>- <div className="conn-form__callback">- <CheckCircle2 size={14} /> Callback URL: <code>{callbackUrl}</code>- </div>- {provider.docUrl && (- <a className="conn-form__doc" href={provider.docUrl} target="_blank" rel="noreferrer">- <ExternalLink size={13} /> Create an OAuth app on {provider.name}- </a>)}<div className="conn-form__actions">- <Button type="submit" size="sm" disabled={busy}>{busy ? 'Saving…' : 'Save OAuth app'}</Button>+ <Button type="button" size="sm" onClick={onSetupApp}>+ <Zap size={15} /> {appSlug ? 'Re-create GitHub App' : 'Set up in one click'}+ </Button></div>- </form>+ </div>+ )}++ {isAdmin && (+ <div className="conn-advanced">+ {isGithub && (+ <button+ type="button"+ className="conn-advanced__toggle"+ onClick={() => setAdvancedOpen((o) => !o)}+ aria-expanded={advancedOpen}+ >+ <span><KeyRound size={14} /> Advanced: use your own OAuth app</span>+ <ChevronDown size={15} className={advancedOpen ? 'conn-list__chev is-open' : 'conn-list__chev'} />+ </button>+ )}+ {advancedOpen && (+ <form className="conn-form" onSubmit={save}>+ {!isGithub && <div className="conn-form__heading"><KeyRound size={15} /> OAuth app credentials</div>}+ <div className="conn-form__grid">+ <div className="form-group">+ <Label htmlFor="src-client-id">Client ID</Label>+ <Input id="src-client-id" value={cfg.client_id} onChange={(e) => setCfg((c) => ({ ...c, client_id: e.target.value }))} placeholder={`${provider.name} OAuth client ID`} autoComplete="off" />+ </div>+ <div className="form-group">+ <Label htmlFor="src-client-secret">Client Secret</Label>+ <Input id="src-client-secret" type="password" value={cfg.client_secret} onChange={(e) => setCfg((c) => ({ ...c, client_secret: e.target.value }))} placeholder={`${provider.name} OAuth client secret`} autoComplete="off" />+ </div>+ </div>+ <div className="conn-form__callback">+ <CheckCircle2 size={14} /> Callback URL: <code>{callbackUrl}</code>+ </div>+ {provider.docUrl && (+ <a className="conn-form__doc" href={provider.docUrl} target="_blank" rel="noreferrer">+ <ExternalLink size={13} /> Create an OAuth app on {provider.name}+ </a>+ )}+ <div className="conn-form__actions">+ <Button type="submit" size="sm" disabled={busy}>{busy ? 'Saving…' : 'Save OAuth app'}</Button>+ </div>+ </form>+ )}+ </div>)}</>);diff --git a/frontend/src/components/settings/connections/ConnectionsHub.jsx b/frontend/src/components/settings/connections/ConnectionsHub.jsxindex 107b1c69..9c84a80f 100644--- a/frontend/src/components/settings/connections/ConnectionsHub.jsx+++ b/frontend/src/components/settings/connections/ConnectionsHub.jsx@@ -104,6 +104,30 @@ export default function ConnectionsHub() {}}, [toast, loadData]);+ // One-click GitHub App setup: fetch the manifest, then POST it to github.com+ // via an auto-submitted form (GitHub only accepts the manifest as a form+ // field). GitHub redirects back to the callback which finishes the setup.+ const onSetupGithubApp = useCallback(async () => {+ try {+ const baseUrl = window.location.origin;+ const redirectUri = `${baseUrl}/connections/github-app/callback`;+ const { manifest, state, post_url } = await api.getGithubAppManifest(baseUrl, redirectUri);+ sessionStorage.setItem('sourceConnectionReturnTo', '/settings/connections');+ const form = document.createElement('form');+ form.method = 'POST';+ form.action = `${post_url}?state=${encodeURIComponent(state)}`;+ const input = document.createElement('input');+ input.type = 'hidden';+ input.name = 'manifest';+ input.value = JSON.stringify(manifest);+ form.appendChild(input);+ document.body.appendChild(form);+ form.submit();+ } catch (err) {+ toast.error(err.message || 'Failed to start GitHub App setup');+ }+ }, [toast]);+const onSaveSourceConfig = useCallback(async (provider, config) => {try {if (provider.provider === 'gitlab') await api.updateGitlabSourceConfig(config);@@ -482,6 +506,7 @@ export default function ConnectionsHub() {onConnectSource={onConnectSource}onDisconnectSource={onDisconnectSource}onSaveSourceConfig={onSaveSourceConfig}+ onSetupGithubApp={onSetupGithubApp}onAddDns={onAddDns}onRemoveDns={onRemoveDns}onTestDns={onTestDns}diff --git a/frontend/src/pages/GithubAppCallback.jsx b/frontend/src/pages/GithubAppCallback.jsxnew file mode 100644index 00000000..535029e3--- /dev/null+++ b/frontend/src/pages/GithubAppCallback.jsx@@ -0,0 +1,75 @@+import { useEffect, useRef, useState } from 'react';+import { useNavigate, useSearchParams } from 'react-router-dom';+import { Github, Loader2 } from 'lucide-react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++// Lands here after the operator confirms the one-click GitHub App on github.com.+// We convert the returned manifest code into stored app credentials, then chain+// straight into the connect flow (install + authorize) so the whole thing is a+// single hop for the user.+const GithubAppCallback = () => {+ const [searchParams] = useSearchParams();+ const navigate = useNavigate();+ const toast = useToast();+ const [error, setError] = useState('');+ const didRun = useRef(false);++ useEffect(() => {+ if (didRun.current) return;+ didRun.current = true;++ async function run() {+ const code = searchParams.get('code');+ const state = searchParams.get('state');+ if (!code || !state) {+ setError('GitHub did not return a valid app-manifest response.');+ return;+ }+ try {+ const result = await api.completeGithubAppManifest(code, state);+ toast.success(`GitHub App "${result.name || result.slug}" created`);+ // Chain into connect: this points at the app install screen, which+ // grants repo access and authorizes in one hop.+ try {+ const redirectUri = `${window.location.origin}/connections/callback/github`;+ sessionStorage.setItem('sourceConnectionReturnTo', '/settings/connections');+ const { auth_url } = await api.startSourceConnection('github', redirectUri);+ window.location.href = auth_url;+ } catch {+ // Credentials are saved; just send them back to finish manually.+ navigate('/settings/connections', { replace: true });+ }+ } catch (err) {+ setError(err.message || 'Failed to finish GitHub App setup.');+ }+ }+ run();+ }, [navigate, searchParams, toast]);++ return (+ <div className="auth-page">+ <div className="auth-card">+ <div className="auth-logo">+ <Github size={32} />+ </div>+ <h1>Setting up GitHub</h1>+ {error ? (+ <>+ <p className="auth-error">{error}</p>+ <button type="button" className="btn btn-primary" onClick={() => navigate('/settings/connections')}>+ Back to Connections+ </button>+ </>+ ) : (+ <div className="sso-loading">+ <Loader2 size={24} className="spinning" />+ <p>Creating your GitHub App and connecting…</p>+ </div>+ )}+ </div>+ </div>+ );+};++export default GithubAppCallback;diff --git a/frontend/src/services/api/sourceConnections.js b/frontend/src/services/api/sourceConnections.jsindex ad7e6400..d09d0f7c 100644--- a/frontend/src/services/api/sourceConnections.js+++ b/frontend/src/services/api/sourceConnections.js@@ -49,6 +49,21 @@ export async function updateGithubSourceConfig(config) {});}+// One-click GitHub App setup (manifest flow). `getGithubAppManifest` returns the+// manifest + state + post_url to POST to github.com; `completeGithubAppManifest`+// converts the returned code into stored app credentials.+export async function getGithubAppManifest(baseUrl, redirectUri) {+ const params = new URLSearchParams({ base_url: baseUrl, redirect_uri: redirectUri });+ return this.request(`/source-connections/admin/github/app-manifest?${params.toString()}`);+}++export async function completeGithubAppManifest(code, state) {+ return this.request('/source-connections/admin/github/app-manifest/complete', {+ method: 'POST',+ body: { code, state },+ });+}+// GitLab mirrors the GitHub surface (same generic connect/disconnect helpers// above, which already take a `provider` argument).diff --git a/frontend/src/styles/pages/_connections.scss b/frontend/src/styles/pages/_connections.scssindex ac773b5e..130bc8e7 100644--- a/frontend/src/styles/pages/_connections.scss+++ b/frontend/src/styles/pages/_connections.scss@@ -516,6 +516,86 @@}// Connect / add form (shared by GitHub config + DNS add)+// One-click GitHub App setup card.+.conn-oneclick {+ display: flex;+ flex-direction: column;+ gap: $space-2;+ padding: $space-4;+ background: var(--accent-bg, rgba(109, 124, 255, 0.08));+ border: 1px solid var(--accent-dim, $border-subtle);+ border-radius: $radius-md;++ &__head {+ display: flex;+ align-items: center;+ gap: $space-2;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ color: $text-primary;++ svg { color: $accent-primary; }+ }++ &__blurb {+ margin: 0;+ font-size: $font-size-xs;+ line-height: 1.5;+ color: $text-tertiary;+ }++ &__done {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-wrap: wrap;+ font-size: $font-size-xs;+ color: $text-secondary;++ svg { color: $success; }++ strong { color: $text-primary; }++ a {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: $accent-primary;+ text-decoration: none;++ &:hover { text-decoration: underline; }+ }+ }+}++// Advanced (manual OAuth app) disclosure.+.conn-advanced {+ display: flex;+ flex-direction: column;+ gap: $space-3;++ &__toggle {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-2;+ padding: $space-2 0;+ background: none;+ border: none;+ color: $text-tertiary;+ font-size: $font-size-sm;+ cursor: pointer;++ span {+ display: flex;+ align-items: center;+ gap: $space-2;+ }++ &:hover { color: $text-secondary; }+ }+}+.conn-form {display: flex;flex-direction: column;