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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ jobs:
run: npx playwright install --with-deps chromium
# Includes: a self-hosted install never loads Google's tag.
- name: Self-host checks
run: npx playwright test e2e/selfhost.spec.ts e2e/google-analytics.spec.ts --project=chromium
run: npx playwright test e2e/selfhost.spec.ts e2e/google-analytics.spec.ts e2e/selfhost-links.spec.ts --project=chromium
env:
E2E_STATIC: "1"

Expand Down
102 changes: 102 additions & 0 deletions dashboard/e2e/selfhost-links.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { expect, test, type Page, type Route } from "@playwright/test";

// A self-hosted install's dashboard links to the install, never to the hosted
// service: its API calls, the address shown for API keys, and the GitHub App
// buttons (which go through the install's own /auth/github/app, so they open
// the install's app). Public docs on docs.coderhelm.com are the one exception.

const ME = {
user_id: "u_1",
team_id: "t_1",
github_login: null,
email: "owner@example.org",
avatar_url: "",
role: "owner",
auth_provider: "email",
mfa_enabled: false,
platform_admin: true,
};

const KEYS = {
keys: [],
scopes: [{ key: "runs:read", label: "Read runs", always: true, allowed: true }],
limits: { default_rate_per_minute: 60, min_rate_per_minute: 1, max_rate_per_minute: 600, max_expiry_days: 365, max_keys: 20 },
};

async function selfHosted(page: Page) {
const outside: string[] = [];
const calls: string[] = [];
const json = (route: Route, body: unknown, status = 200) =>
route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
await page.route((url) => url.pathname === "/runtime-config.js", (route) =>
route.fulfill({
contentType: "text/javascript",
body: `window.__CODERHELM_CONFIG__ = ${JSON.stringify({ apiUrl: "", streamUrl: "", selfHosted: true, siteUrl: null, supportEmail: "it@example.org" })};`,
}),
);
await page.route((url) => !["localhost", "127.0.0.1"].includes(url.hostname), (route) => {
outside.push(route.request().url());
return route.abort();
});
await page.route((url) => ["localhost", "127.0.0.1"].includes(url.hostname) && /^\/(api|auth)\//.test(url.pathname), (route) => {
const u = new URL(route.request().url());
calls.push(u.pathname);
const p = u.pathname;
if (p === "/api/me") return json(route, ME);
if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 });
if (p === "/api/banners") return json(route, { banners: [] });
if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] });
if (p === "/api/api-keys") return json(route, KEYS);
if (p === "/api/repos") return json(route, { repos: [] });
if (p === "/api/github/installation-status") return json(route, { installed: false });
if (p === "/api/integrations") return json(route, { can_edit: true, migrated: 0, items: [] });
return json(route, {});
});
return { outside, calls };
}

/** Every link on the page that goes to coderhelm.com, other than the public docs. */
async function hostedLinks(page: Page): Promise<string[]> {
const hrefs = await page.locator("a[href]").evaluateAll((as) => as.map((a) => (a as HTMLAnchorElement).href));
return hrefs.filter((h) => {
const host = new URL(h).hostname;
return (host === "coderhelm.com" || host.endsWith(".coderhelm.com")) && host !== "docs.coderhelm.com";
});
}

test("API keys: the install's own address, and its own API", async ({ page, baseURL }) => {
const { outside, calls } = await selfHosted(page);
await page.goto("/settings/api-keys");
await expect(page.getByText("How keys work")).toBeVisible();
const origin = new URL(baseURL!).origin;
await expect(page.getByText(`Send the key as`).locator("code").nth(1)).toHaveText(origin);
await expect(page.getByText("api.coderhelm.com")).toHaveCount(0);
expect(calls).toContain("/api/api-keys");
expect(await hostedLinks(page)).toEqual([]);
expect(outside.filter((u) => u.includes("coderhelm.com"))).toEqual([]);
});

test("Repositories: Install the GitHub App opens the install's own app", async ({ page, baseURL }) => {
const { outside } = await selfHosted(page);
await page.goto("/settings/repos");
const install = page.getByRole("link", { name: "Install the GitHub App" });
await expect(install).toBeVisible();
await expect(install).toHaveAttribute("href", `${new URL(baseURL!).origin}/auth/github/app`);
expect(await hostedLinks(page)).toEqual([]);
expect(outside.filter((u) => u.includes("coderhelm.com"))).toEqual([]);
});

test("GitHub settings: Install goes through the install, with its state", async ({ page, baseURL }) => {
await selfHosted(page);
let opened = "";
await page.route((url) => url.pathname === "/auth/github/app", (route) => {
opened = route.request().url();
return route.fulfill({ status: 200, contentType: "text/html", body: "<p>GitHub</p>" });
});
await page.goto("/settings/integrations/github");
const button = page.getByRole("button", { name: /^Install/ }).first();
await expect(button).toBeVisible();
expect(await hostedLinks(page)).toEqual([]);
await button.click();
await expect.poll(() => opened).toContain(`${new URL(baseURL!).origin}/auth/github/app?state=`);
});
2 changes: 1 addition & 1 deletion dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "node scripts/ui-lint.mjs",
"lint": "node scripts/ui-lint.mjs && node scripts/no-hosted-links.mjs",
"typecheck": "tsc --noEmit",
"openapi:fields": "node scripts/openapi-fields.mjs",
"check:openapi": "node scripts/openapi-fields.mjs --check",
Expand Down
54 changes: 54 additions & 0 deletions dashboard/scripts/no-hosted-links.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env node
// No hardcoded hosted addresses in the dashboard. The same build serves the
// hosted service and every self-hosted install, so the API, the stream and
// the GitHub App come from lib/runtime-config.ts (apiBase, apiOrigin,
// githubAppUrl), never from a literal. Runs with `npm run lint`.
//
// Flags app., api., stream. and auth.coderhelm.com, the marketing site, and
// github.com/apps/coderhelm (the hosted GitHub App) anywhere in src/ outside
// the files below. Comments are not checked. docs.coderhelm.com is always fine.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");

/** Files that may name a hosted address, and why. */
const ALLOWED = {
"src/lib/runtime-config.ts": "the hosted defaults, used only when no runtime config says otherwise",
"src/components/google-analytics.tsx": "a hostname check that keeps the hosted dashboard's analytics off every other host; not a link",
};

const PATTERN = /\b(?:app|api|stream|auth)\.coderhelm\.com|:\/\/(?:www\.)?coderhelm\.com|github\.com\/apps\/coderhelm\b/i;

function walk(dir, out = []) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) walk(p, out);
else if (/\.(tsx?|mjs|js)$/.test(e.name)) out.push(p);
}
return out;
}

const found = [];
for (const file of walk(path.join(ROOT, "src"))) {
const rel = path.relative(ROOT, file).split(path.sep).join("/");
if (ALLOWED[rel]) continue;
fs.readFileSync(file, "utf8")
.split("\n")
.forEach((line, i) => {
const t = line.trim();
if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return;
const m = line.match(PATTERN);
if (m) found.push(`${rel}:${i + 1}: ${m[0]}: ${t.slice(0, 160)}`);
});
}

if (found.length) {
console.error(
"Hardcoded hosted addresses. Use apiBase(), apiOrigin() or githubAppUrl() from lib/runtime-config.ts, or add the file to ALLOWED with the reason:\n" +
found.join("\n"),
);
process.exit(1);
}
console.log("No hardcoded hosted addresses.");
3 changes: 2 additions & 1 deletion dashboard/src/app/settings/api-keys/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useConfirm } from "@/components/confirm-dialog";
import { useToast } from "@/components/toast";
import { useCan } from "@/hooks/use-can";
import { relativeTime } from "@/lib/team";
import { apiOrigin } from "@/lib/runtime-config";
import {
API_DOCS_URL,
apiKeysApi,
Expand Down Expand Up @@ -208,7 +209,7 @@ function ApiKeysPage() {
</h2>
<ul className="list-disc space-y-1 pl-5 text-sm text-zinc-400">
<li>
Send the key as <Code>Authorization: Bearer chk_...</Code> to <Code>https://api.coderhelm.com</Code>.
Send the key as <Code>Authorization: Bearer chk_...</Code> to <Code>{apiOrigin()}</Code>.
</li>
<li>The key is shown once, when you create it. Coderhelm keeps only a fingerprint of it.</li>
<li>
Expand Down
6 changes: 3 additions & 3 deletions dashboard/src/app/settings/integrations/github/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useCan } from "@/hooks/use-can";
import { api, type Integration, type Repo } from "@/lib/api";
import { githubAppUrl } from "@/lib/runtime-config";
import { findCard, INTEGRATION_STATUS } from "@/lib/integration-status";
import { Skeleton } from "@/components/skeleton";
import { RoleGuard } from "@/components/role-guard";
Expand All @@ -19,7 +20,6 @@ import { HybridAppChoice } from "@/components/hybrid-app-choice";
import { ExternalLinkIcon, GitHubIcon } from "@/components/icons";
import { buttonClass, linkButton } from "@/components/ui";

const GITHUB_APP_INSTALL_URL = "https://github.com/apps/coderhelm/installations/new";
const STATE_STORAGE_KEY = "gh_install_state";

/** `url` when it is an http(s) address, else null. */
Expand Down Expand Up @@ -170,7 +170,7 @@ function GitHubSettingsPage() {
const handleInstallClick = () => {
const state = crypto.randomUUID();
sessionStorage.setItem(STATE_STORAGE_KEY, state);
window.location.href = `${GITHUB_APP_INSTALL_URL}?state=${state}`;
window.location.href = githubAppUrl({ state });
};

const header = (
Expand Down Expand Up @@ -250,7 +250,7 @@ function GitHubSettingsPage() {
<StatusPill tone="success">Connected</StatusPill>
{installationId && (
<a
href={`https://github.com/apps/coderhelm/installations/${installationId}`}
href={githubAppUrl({ installationId })}
target="_blank"
rel="noopener noreferrer"
className={`${buttonClass("secondary", "sm")} gap-1.5`}
Expand Down
5 changes: 3 additions & 2 deletions dashboard/src/app/settings/repos/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useCan } from "@/hooks/use-can";
import { ANY_CHANGE } from "@/lib/capabilities";
import { Suspense, useCallback, useEffect, useState } from "react";
import { api, type Repo } from "@/lib/api";
import { githubAppUrl } from "@/lib/runtime-config";
import { RoleGuard } from "@/components/role-guard";
import { useToast } from "@/components/toast";
import { Page, PageHeader } from "@/components/page";
Expand Down Expand Up @@ -221,7 +222,7 @@ function ReposPage() {
title="No repositories connected yet"
action={
<>
<a href="https://github.com/apps/coderhelm" className={secondaryButton}>
<a href={githubAppUrl()} className={secondaryButton}>
Install the GitHub App
</a>
{canManage && (
Expand Down Expand Up @@ -260,7 +261,7 @@ function ReposPage() {
<span>{readProblem(repo.onboard_error).text}</span>
{canManage &&
(readProblem(repo.onboard_error).fixInGitHub ? (
<a href="https://github.com/apps/coderhelm/installations/new" target="_blank" rel="noreferrer" className={buttonClass("secondary", "sm")}>
<a href={githubAppUrl()} target="_blank" rel="noreferrer" className={buttonClass("secondary", "sm")}>
Fix access in GitHub
</a>
) : (
Expand Down
10 changes: 5 additions & 5 deletions dashboard/src/components/client-shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { SectionTabs } from "./section-tabs";
import { inSettings, SettingsNav } from "./settings-nav";
import { buttonClass } from "./ui";
import { AlertCircleIcon, InfoIcon, LogFindingsIcon, WarningIcon, XIcon } from "./icons";
import { apiBase, runtimeConfig, siteUrl } from "@/lib/runtime-config";
import { apiBase, githubAppUrl, runtimeConfig, siteUrl } from "@/lib/runtime-config";
import { SetupBanner } from "@/components/setup-banner";
import { CopyButton } from "./copy-button";
import { openInChromeHref, signInProblem, type SignInProblem } from "@/lib/sign-in-errors";
Expand Down Expand Up @@ -65,8 +65,8 @@ interface User {
/** Who sees the platform admin pages. The server checks again on every call. */
function isPlatformAdmin(user: User | null): boolean {
if (typeof user?.platform_admin === "boolean") return user.platform_admin;
// A gateway from before the field: the hosted admin.
return user?.email === "admin@coderhelm.com";
// A gateway from before the field: the hosted admin, on the hosted dashboard only.
return !isSelfHosted() && user?.email === "admin@coderhelm.com";
}

const NAV_ICONS: Record<NavIconKey, ReactNode> = {
Expand Down Expand Up @@ -333,7 +333,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) {
</p>
<div className="flex flex-col items-center gap-3">
<a
href="https://github.com/apps/coderhelm/installations/new"
href={githubAppUrl()}
target="_blank"
rel="noopener noreferrer"
className={buttonClass("primary")}
Expand All @@ -343,7 +343,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) {
<button
type="button"
onClick={() => {
void navigator.clipboard?.writeText("https://github.com/apps/coderhelm/installations/new").catch(() => {});
void navigator.clipboard?.writeText(githubAppUrl()).catch(() => {});
}}
className={buttonClass("secondary")}
>
Expand Down
6 changes: 3 additions & 3 deletions dashboard/src/lib/api-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// own programs. The gateway keeps only a hash of each key; the key itself is
// in the create answer and nowhere else.

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "https://api.coderhelm.com";
import { apiBase, apiOrigin } from "./runtime-config";

/** Where the public API is documented. */
export const API_DOCS_URL = "https://docs.coderhelm.com/api";
Expand Down Expand Up @@ -54,7 +54,7 @@ export interface NewApiKey {
}

async function request<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
const res = await fetch(`${apiBase()}${path}`, {
...options,
credentials: "include",
cache: "no-store",
Expand All @@ -81,5 +81,5 @@ export const apiKeysApi = {

/** A first request to try a new key with. */
export function curlExample(token: string): string {
return `curl https://api.coderhelm.com/api/me \\\n -H "Authorization: Bearer ${token}"`;
return `curl ${apiOrigin()}/api/me \\\n -H "Authorization: Bearer ${token}"`;
}
4 changes: 2 additions & 2 deletions dashboard/src/lib/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// stand between a draft and anything going out. Off unless the team's
// `plugins` flag is on.

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "https://api.coderhelm.com";
import { apiBase } from "./runtime-config";

export type Risk = "read" | "write" | "consequential";
export type TrackKind = "branch" | "tag" | "sha";
Expand Down Expand Up @@ -256,7 +256,7 @@ export class PluginError extends Error {
}

async function call<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
const res = await fetch(`${apiBase()}${path}`, {
...init,
credentials: "include",
cache: "no-store",
Expand Down
13 changes: 13 additions & 0 deletions dashboard/src/lib/runtime-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ export function apiOrigin(): string {
return typeof window === "undefined" ? "" : window.location.origin;
}

/**
* This deployment's GitHub App on GitHub: the gateway redirects to its own
* app (a self-hosted install's app, not the hosted one). `state` starts a new
* installation; `installationId` opens that installation's settings.
*/
export function githubAppUrl(opts: { state?: string; installationId?: number | string } = {}): string {
const q = new URLSearchParams();
if (opts.state) q.set("state", opts.state);
if (opts.installationId !== undefined && opts.installationId !== "") q.set("installation_id", String(opts.installationId));
const qs = q.toString();
return `${apiOrigin()}/auth/github/app${qs ? `?${qs}` : ""}`;
}

export function isSelfHosted(): boolean {
return runtimeConfig().selfHosted === true;
}
Expand Down
Loading