From d9ef6a0b9babb1cd5f201788d51565b88bc6901f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 12:12:27 -0400 Subject: [PATCH] Hosted two-factor sign-in: Settings, Sign-in per team, held screen, Security, docs Settings, Sign-in opens on hosted with the team's switch, how many people have no second factor, the email notice and a reset that reaches every team. The shell learns a held session from the server's two_factor_required answer, so sessions that aren't held make no extra call. Security shows the app code after Google or GitHub and keeps it on while a team requires it. New docs page Concepts, Sign-in and two-factor, and a card on the Security page. --- dashboard/e2e/hosted-2fa.spec.ts | 277 +++++++++++++++++++ dashboard/e2e/wide-data/settings.ts | 4 + dashboard/src/app/settings/security/page.tsx | 74 +++-- dashboard/src/app/settings/sign-in/page.tsx | 189 +++++++------ dashboard/src/components/client-shell.tsx | 44 ++- dashboard/src/components/settings-items.tsx | 2 +- dashboard/src/lib/api.ts | 22 +- docs/content/docs/concepts/meta.json | 2 +- docs/content/docs/concepts/roles.mdx | 4 +- docs/content/docs/concepts/sign-in.mdx | 47 ++++ docs/published-pages.json | 1 + src/content/site.ts | 1 + 12 files changed, 545 insertions(+), 122 deletions(-) create mode 100644 dashboard/e2e/hosted-2fa.spec.ts create mode 100644 docs/content/docs/concepts/sign-in.mdx diff --git a/dashboard/e2e/hosted-2fa.spec.ts b/dashboard/e2e/hosted-2fa.spec.ts new file mode 100644 index 00000000..1b9c75d4 --- /dev/null +++ b/dashboard/e2e/hosted-2fa.spec.ts @@ -0,0 +1,277 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import path from "node:path"; + +// The hosted deployment: each team's admins can require two-factor sign-in +// for that team, and a person's one second factor is asked for after every +// way in. Settings, Sign-in (no domains, the team's switch, how many have no +// second factor, the emails, a reset that reaches every team), the held +// screen, the Security page after Google, and the code step. Every API call +// is mocked; screenshots at 1440 and 390 go to E2E_SHOTS_DIR. + +const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); +const WIDTHS = [1440, 390] as const; + +const ME = { + user_id: "USER#owner", + team_id: "TEAM#acme", + github_login: null, + email: "owner@example.org", + avatar_url: "", + role: "owner", + auth_provider: "email", + mfa_enabled: true, +}; + +const PEOPLE = [ + { user_id: "owner", email: "owner@example.org", name: "Olu Owner", github_login: "", role: "owner", two_factor: "cognito", is_self: true }, + { user_id: "ann", email: "ann@example.org", name: "Ann Lee", github_login: "", role: "member", two_factor: "app", is_self: false }, + { user_id: "bo", email: "bo@example.org", name: "", github_login: "bo-codes", role: "member", two_factor: null, is_self: false }, +]; + +interface State { + me: Record | null; + mine: Record; + settings: Record; + puts: Record[]; + resets: { user: string; body: Record }[]; + verified: string[]; + /** How many times the page asked for /api/users/2fa. */ + statusReads: number; +} + +async function mock(page: Page, over: Partial = {}): Promise { + const state: State = { + me: ME, + mine: { self_hosted: false, required: false, held: false, must_keep: false, session_has_2fa: true, signed_in_with: "password", set_up: "cognito", fits: "cognito" }, + settings: { + self_hosted: false, + is_org: true, + domains: [], + require_2fa: false, + require_2fa_since: null, + pending_invites: 0, + people: PEOPLE, + without_2fa: 1, + api_keys: [ + { id: "k1", name: "Nightly report", created_by: "Olu Owner" }, + { id: "k2", name: "Old export", created_by: "bo-codes", made_before_rule: true, maker_on_team: true, maker_two_factor: null }, + ], + your_session_has_2fa: true, + }, + puts: [], + resets: [], + verified: [], + statusReads: 0, + ...over, + }; + 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({ selfHosted: false })};` }), + ); + await page.route((url) => !["localhost", "127.0.0.1"].includes(url.hostname), (route) => route.abort()); + await page.route((url) => ["localhost", "127.0.0.1"].includes(url.hostname) && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const req = route.request(); + const p = new URL(req.url()).pathname; + const body = () => JSON.parse(req.postData() || "{}"); + if (p === "/api/me") return state.me ? json(route, state.me) : json(route, { error: "unauthorized" }, 401); + if (p === "/api/users/2fa") { + state.statusReads += 1; + return json(route, state.mine); + } + // A held session: the server refuses everything but the setup screens. + if (state.mine.held && !["/api/me", "/api/users/2fa", "/api/users/2fa/app/setup", "/api/users/2fa/app/verify"].includes(p)) { + return json(route, { error: "This team requires two-factor sign-in. Set it up to continue.", code: "two_factor_required" }, 403); + } + if (p === "/api/usage") return json(route, { month: "2026-10", 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: "TEAM#acme", org: "Acme", status: "active", current: true }, + { team_id: "TEAM#side", org: "Side project", status: "active", current: false }, + ], + }); + } + if (p === "/api/sign-in" && req.method() === "GET") return json(route, state.settings); + if (p === "/api/sign-in" && req.method() === "PUT") { + const b = body(); + state.puts.push(b); + state.settings = { ...state.settings, ...b, ...(b.require_2fa ? { require_2fa_since: "2026-10-27T12:00:00Z" } : {}) }; + return json(route, { + domains: [], + require_2fa: state.settings.require_2fa, + require_2fa_since: state.settings.require_2fa_since, + notified: b.require_2fa ? 1 : 0, + }); + } + const reset = /^\/api\/users\/([^/]+)\/2fa\/reset$/.exec(p); + if (reset) { + state.resets.push({ user: decodeURIComponent(reset[1]), body: body() }); + return json(route, { status: "reset" }); + } + if (p === "/api/users/2fa/app/setup") { + return json(route, { secret: "JBSWY3DPEHPK3PXP", qr_uri: "otpauth://totp/Coderhelm:bo%40example.org?secret=JBSWY3DPEHPK3PXP&issuer=Coderhelm" }); + } + if (p === "/api/users/2fa/app/verify") { + state.verified.push(body().code); + state.mine = { ...state.mine, held: false, session_has_2fa: true, set_up: "app" }; + return json(route, { status: "enabled" }); + } + if (p === "/auth/2fa/verify") { + const code = body().code; + if (code !== "123456") return json(route, { error: "wrong", code: "wrong_code" }, 401); + state.verified.push(code); + state.me = { ...ME, email: "ann@example.org", role: "member", auth_provider: "google", mfa_enabled: false }; + state.mine = { ...state.mine, session_has_2fa: true, signed_in_with: "google", set_up: "app", fits: "app" }; + return json(route, { status: "ok", team_id: "TEAM#acme" }); + } + if (p === "/auth/logout") return json(route, {}); + return json(route, {}); + }); + return state; +} + +async function shot(page: Page, name: string, width: number) { + await page.screenshot({ path: path.join(SHOTS_DIR, `${name}-${width}.png`), fullPage: true }); +} + +async function noSidewaysScroll(page: Page) { + const over = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(over).toBeLessThanOrEqual(1); +} + +for (const width of WIDTHS) { + test.describe(`hosted, at ${width}px`, () => { + test.use({ viewport: { width, height: width < 600 ? 844 : 900 } }); + + test("Settings, Sign-in: the team's switch, who has none, the emails and a reset that reaches every team", async ({ page }) => { + const state = await mock(page); + await page.goto("/settings/sign-in"); + await expect(page.getByRole("heading", { name: "Sign-in", level: 1 })).toBeVisible(); + await expect(page.getByText("everyone on this team must use two-factor sign-in", { exact: false }).first()).toBeVisible(); + // Hosted has no organization: no domains, no "for self-hosted installs" dead end. + await expect(page.getByText("Who may join")).toHaveCount(0); + await expect(page.getByText("for self-hosted installs")).toHaveCount(0); + await expect(page.getByText("Require two-factor sign-in for this team")).toBeVisible(); + await expect(page.getByTestId("without-2fa")).toHaveText("1 of 3 people hasn't set it up yet."); + await expect(page.getByTestId("people-2fa")).toContainText("Not set up"); + await expect(page.getByTestId("api-keys").getByTestId("key-review")).toHaveCount(1); + await noSidewaysScroll(page); + await shot(page, "hosted-sign-in-settings", width); + + await page.getByTestId("require-2fa").click(); + const confirm = page.getByRole("alertdialog").or(page.getByRole("dialog")); + await expect(confirm).toContainText("Require two-factor sign-in for everyone on this team?"); + await expect(confirm).toContainText("1 person hasn't set it up yet. We'll email them now."); + await shot(page, "hosted-sign-in-require-confirm", width); + await page.getByRole("button", { name: "Require it" }).click(); + await expect.poll(() => state.puts.at(-1)).toEqual({ require_2fa: true }); + await expect(page.getByTestId("require-2fa")).toHaveAttribute("aria-checked", "true"); + await expect(page.getByText("Emailed 1 person who hasn't set it up.", { exact: false })).toBeVisible(); + + const ann = page.getByTestId("people-2fa").getByRole("listitem").filter({ hasText: "Ann Lee" }); + await ann.getByRole("button", { name: "Reset" }).click(); + const dialog = page.getByTestId("reset-2fa-dialog"); + await expect(dialog).toContainText("same on every team they're on"); + await dialog.getByLabel("How did you check it's them?").fill("Video call, saw their badge"); + await shot(page, "hosted-sign-in-reset", width); + await dialog.getByRole("button", { name: "Reset" }).click(); + await expect.poll(() => state.resets).toEqual([{ user: "ann", body: { verified_how: "Video call, saw their badge" } }]); + }); + + test("the switch waits until the admin's own session used a code", async ({ page }) => { + await mock(page, { + settings: { + self_hosted: false, is_org: true, domains: [], require_2fa: false, require_2fa_since: null, pending_invites: 0, + people: PEOPLE, without_2fa: 1, api_keys: [], your_session_has_2fa: false, + }, + }); + await page.goto("/settings/sign-in"); + await expect(page.getByTestId("require-2fa")).toBeDisabled(); + await expect(page.getByTestId("set-up-yours-first")).toContainText("require it for everyone on this team"); + await noSidewaysScroll(page); + }); + + test("the Settings hub lists Sign-in on hosted", async ({ page }) => { + await mock(page); + await page.goto("/settings"); + await expect(page.getByRole("link", { name: /Sign-in/ }).first()).toBeVisible(); + }); + + test("a session that isn't held makes no extra call for it", async ({ page }) => { + const state = await mock(page); + await page.goto("/settings"); + await expect(page.getByRole("link", { name: /Sign-in/ }).first()).toBeVisible(); + await page.waitForLoadState("networkidle", { timeout: 15_000 }).catch(() => {}); + await expect(page.getByTestId("two-factor-gate")).toHaveCount(0); + expect(state.statusReads).toBe(0); + }); + + test("a member held by the team's rule sees only the setup screen", async ({ page }) => { + const state = await mock(page, { + me: { ...ME, email: "bo@example.org", role: "member", auth_provider: "github", github_login: "bo-codes", mfa_enabled: false }, + mine: { self_hosted: false, required: true, held: true, must_keep: true, session_has_2fa: false, signed_in_with: "github", set_up: null, fits: "app" }, + }); + await page.goto("/settings/security"); + const gate = page.getByTestId("two-factor-gate"); + await expect(gate.getByRole("heading", { name: "Set up two-factor sign-in" })).toBeVisible(); + await expect(gate).toContainText("This team requires two-factor sign-in."); + await expect(page.getByTestId("main-nav")).toHaveCount(0); + await noSidewaysScroll(page); + await shot(page, "hosted-two-factor-gate", width); + await gate.getByRole("button", { name: "Set up an authenticator app" }).click(); + await gate.getByRole("button", { name: "Next: enter a code" }).click(); + await gate.getByLabel("Code from the app").fill("654321"); + await gate.getByRole("button", { name: "Turn on two-factor sign-in" }).click(); + await expect.poll(() => state.verified).toEqual(["654321"]); + await expect(page.getByTestId("two-factor-gate")).toHaveCount(0); + }); + + test("Security after Google: the app code, kept on while a team requires it", async ({ page }) => { + await mock(page, { + me: { ...ME, email: "ann@example.org", role: "member", auth_provider: "google", mfa_enabled: false }, + mine: { self_hosted: false, required: false, held: false, must_keep: true, session_has_2fa: true, signed_in_with: "google", set_up: "app", fits: "app" }, + }); + await page.goto("/settings/security"); + await expect(page.getByTestId("app-two-step-status")).toHaveText("Two-factor sign-in is on"); + await expect(page.getByText("A team you're on requires it, so it stays on.")).toBeVisible(); + await expect(page.getByRole("button", { name: "Turn off two-factor sign-in" })).toHaveCount(0); + await noSidewaysScroll(page); + await shot(page, "hosted-security-google", width); + }); + + test("Security after Google with no factor yet offers the app code", async ({ page }) => { + await mock(page, { + me: { ...ME, email: "cy@example.org", role: "member", auth_provider: "google", mfa_enabled: false }, + mine: { self_hosted: false, required: false, held: false, must_keep: false, session_has_2fa: false, signed_in_with: "google", set_up: null, fits: "app" }, + }); + await page.goto("/settings/security"); + await expect(page.getByTestId("app-two-step-status")).toHaveText("Two-factor sign-in is off"); + await expect(page.getByRole("button", { name: "Turn on two-factor sign-in" })).toBeVisible(); + await shot(page, "hosted-security-google-off", width); + }); + + test("Security after Google when the code is on the password account says how to sign in", async ({ page }) => { + await mock(page, { + me: { ...ME, email: "owner@example.org", auth_provider: "google", mfa_enabled: false }, + mine: { self_hosted: false, required: false, held: false, must_keep: false, session_has_2fa: false, signed_in_with: "google", set_up: "cognito", fits: "app" }, + }); + await page.goto("/settings/security"); + await expect(page.getByTestId("code-on-password-account")).toContainText("Sign in with your email and password"); + await expect(page.getByRole("button", { name: "Turn on two-factor sign-in" })).toHaveCount(0); + }); + + test("after Google, the code screen comes before the app", async ({ page }) => { + const state = await mock(page, { me: null }); + await page.goto("/?two_factor=1"); + const form = page.getByTestId("second-step"); + await expect(form).toContainText("Enter the code from your authenticator app to finish signing in."); + await noSidewaysScroll(page); + await shot(page, "hosted-second-step", width); + await form.getByLabel("Six digit code").fill("123456"); + await form.getByRole("button", { name: "Sign in", exact: true }).click(); + await expect.poll(() => state.verified).toEqual(["123456"]); + }); + }); +} diff --git a/dashboard/e2e/wide-data/settings.ts b/dashboard/e2e/wide-data/settings.ts index 30b017ba..05818df9 100644 --- a/dashboard/e2e/wide-data/settings.ts +++ b/dashboard/e2e/wide-data/settings.ts @@ -230,6 +230,10 @@ export const settingsData: Handler = ({ method, path, url }) => { }] }; } if (p === "/api/users") return { users: USERS }; + // Your own two-factor sign-in (both deployments): kept on by a team's rule. + if (p === "/api/users/2fa") { + return { self_hosted: false, required: false, held: false, must_keep: true, session_has_2fa: true, signed_in_with: "password", set_up: "cognito", fits: "cognito" }; + } // Sign-in (self-hosted): long domains, long names and an unbroken email. if (p === "/api/sign-in") { return { diff --git a/dashboard/src/app/settings/security/page.tsx b/dashboard/src/app/settings/security/page.tsx index b6aa54ca..c3c54188 100644 --- a/dashboard/src/app/settings/security/page.tsx +++ b/dashboard/src/app/settings/security/page.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import QRCode from "qrcode"; -import { api } from "@/lib/api"; +import { api, errorStatus } from "@/lib/api"; import { useToast } from "@/components/toast"; import { useConfirm } from "@/components/confirm-dialog"; import { Skeleton } from "@/components/skeleton"; @@ -51,13 +51,13 @@ export default function SecurityPage() { const [mfaEnabled, setMfaEnabled] = useState(false); const [mfaLoading, setMfaLoading] = useState(false); - // A self-hosted install: Google and GitHub sign-ins get Coderhelm's own - // authenticator-app codes. + // Google and GitHub sign-ins get Coderhelm's own authenticator-app codes; + // a person has one second factor, asked for however they sign in. const [mine, setMine] = useState(null); const [appStep, setAppStep] = useState<"idle" | "setup" | "off">("idle"); const [offCode, setOffCode] = useState(""); const loadMine = useCallback(() => { - if (isSelfHosted()) api.myTwoFactor().then(setMine, () => setMine(null)); + api.myTwoFactor().then(setMine, () => setMine(null)); }, []); useEffect(loadMine, [loadMine]); @@ -80,6 +80,11 @@ export default function SecurityPage() { useEffect(loadMe, [loadMe]); const isOAuth = authProvider === "github" || authProvider === "google"; + // It stays on while a team they're on (self-hosted: the organization) requires it. + const mustKeep = !!(mine?.must_keep ?? mine?.required); + const keepWords = isSelfHosted() + ? "Your organization requires it, so it stays on." + : "A team you're on requires it, so it stays on."; const header = (
@@ -191,8 +196,17 @@ export default function SecurityPage() { await api.mfaDisable(); setMfaEnabled(false); toast(`${TWO_STEP} is off`); - } catch { - toast(`Could not turn off ${TWO_STEP.toLowerCase()}`, "error"); + loadMine(); + } catch (e) { + const status = errorStatus(e); + toast( + status === 403 + ? `To turn it off, sign out and sign in again with your code first.` + : status === 409 + ? keepWords + : `Could not turn off ${TWO_STEP.toLowerCase()}`, + "error", + ); } finally { setMfaLoading(false); } @@ -218,7 +232,7 @@ export default function SecurityPage() { {login ? as {login} : null}

- Your password and {TWO_STEP.toLowerCase()} are managed in your {provider.name} account. + Your password and {provider.name}'s own {TWO_STEP.toLowerCase()} are managed in your {provider.name} account.

{provider.settings && ( @@ -230,26 +244,33 @@ export default function SecurityPage() { )} - {mine?.self_hosted && ( + {mine && (
-

- - - {mine.set_up === "app" ? "Two-factor sign-in is on" : "Two-factor sign-in is off"} - -

- {mine.set_up !== "app" && appStep === "idle" && ( + {mine.set_up === "cognito" && ( +

+ Your two-factor code is on your password account. Sign in with your email and password, then enter the code from your authenticator app. +

+ )} + {mine.set_up !== "cognito" && ( +

+ + + {mine.set_up === "app" ? "Two-factor sign-in is on" : "Two-factor sign-in is off"} + +

+ )} + {!mine.set_up && appStep === "idle" && ( )} - {mine.set_up !== "app" && appStep === "setup" && ( + {!mine.set_up && appStep === "setup" && ( setAppStep("idle")} @@ -260,7 +281,10 @@ export default function SecurityPage() { }} /> )} - {mine.set_up === "app" && !mine.required && appStep !== "off" && ( + {mine.set_up === "app" && mustKeep && ( +

{keepWords}

+ )} + {mine.set_up === "app" && !mustKeep && appStep !== "off" && ( @@ -371,17 +395,23 @@ export default function SecurityPage() { {mfaEnabled ? `${TWO_STEP} is on` : `${TWO_STEP} is off`}

- {mfaStep === "idle" && !mfaEnabled && ( + {mfaStep === "idle" && !mfaEnabled && mine?.set_up === "app" && ( +

+ You have two-factor sign-in with an authenticator app, set up after Google or GitHub. Signing in with your password asks for that code too. +

+ )} + + {mfaStep === "idle" && !mfaEnabled && mine?.set_up !== "app" && ( )} - {mfaStep === "idle" && mfaEnabled && mine?.required && ( -

Your organization requires it, so it stays on.

+ {mfaStep === "idle" && mfaEnabled && mustKeep && ( +

{keepWords}

)} - {mfaStep === "idle" && mfaEnabled && !mine?.required && ( + {mfaStep === "idle" && mfaEnabled && !mustKeep && ( diff --git a/dashboard/src/app/settings/sign-in/page.tsx b/dashboard/src/app/settings/sign-in/page.tsx index e9efac13..820b9db0 100644 --- a/dashboard/src/app/settings/sign-in/page.tsx +++ b/dashboard/src/app/settings/sign-in/page.tsx @@ -12,6 +12,7 @@ import { useToast } from "@/components/toast"; import { useConfirm } from "@/components/confirm-dialog"; import { Field, SettingsSection, Switch } from "@/components/settings"; import { api, errorStatus, type SignInSettings } from "@/lib/api"; +import { isSelfHosted } from "@/lib/runtime-config"; import { buttonClass, fullWidthOnPhone, linkButton, smallSecondaryButton } from "@/components/ui"; export default function SignInSettingsGuarded() { @@ -44,11 +45,18 @@ function SignInSettingsPage() { }, []); useEffect(load, [load]); + // A self-hosted install is one organization (who may join, and one rule); + // on hosted each team has its own rule. + const selfHosted = data ? data.self_hosted : isSelfHosted(); const header = (
); @@ -76,20 +84,13 @@ function SignInSettingsPage() { ); } - if (!data.self_hosted) { - return ( - - {header} -

These settings are for self-hosted installs.

-
- ); - } - const domains = data.domains ?? []; const people = data.people ?? []; const keys = data.api_keys ?? []; const required = !!data.require_2fa; const withFactor = people.filter((p) => p.two_factor).length; + const without = data.without_2fa ?? people.length - withFactor; + const everyone = selfHosted ? "everyone" : "everyone on this team"; const saveDomains = async (next: string[]) => { setSaving(true); @@ -129,12 +130,11 @@ function SignInSettingsPage() { const setRequired = async (on: boolean) => { if (on) { - const missing = people.length - withFactor; const ok = await confirm({ - title: "Require two-factor sign-in for everyone?", + title: `Require two-factor sign-in for ${everyone}?`, message: - missing > 0 - ? `${missing} ${missing === 1 ? "person hasn't" : "people haven't"} set it up yet. At their next request they'll see a setup screen, and nothing else works until they finish. API keys keep working.` + without > 0 + ? `${without} ${without === 1 ? "person hasn't" : "people haven't"} set it up yet. We'll email ${without === 1 ? "them" : "each of them"} now. At their next request they'll see a setup screen, and nothing else works until they finish. API keys keep working.` : "Everyone has set it up. Anyone who joins later sets it up at their first sign-in. API keys keep working.", confirmLabel: "Require it", }); @@ -152,7 +152,13 @@ function SignInSettingsPage() { try { const r = await api.updateSignInSettings({ require_2fa: on }); setData({ ...data, require_2fa: r.require_2fa, require_2fa_since: r.require_2fa_since }); - toast(on ? "Two-factor sign-in is required" : "Two-factor sign-in is no longer required"); + toast( + !on + ? "Two-factor sign-in is no longer required" + : r.notified + ? `Two-factor sign-in is required. Emailed ${r.notified} ${r.notified === 1 ? "person who hasn't" : "people who haven't"} set it up.` + : "Two-factor sign-in is required", + ); } catch (e) { toast(e instanceof Error ? e.message : "Couldn't save. Try again.", "error"); } finally { @@ -166,67 +172,69 @@ function SignInSettingsPage() { {header}
- -
-

- {data.pending_invites - ? `${data.pending_invites} ${data.pending_invites === 1 ? "invite is" : "invites are"} waiting. ` - : ""} - - Invite people in Team - -

-
-

Allowed email domains

- {domains.length === 0 ? ( -

- None: only people you invite can join. -

- ) : ( -
    - {domains.map((d) => ( -
  • - {d} - -
  • - ))} -
- )} + {selfHosted && ( + +
+

+ {data.pending_invites + ? `${data.pending_invites} ${data.pending_invites === 1 ? "invite is" : "invites are"} waiting. ` + : ""} + + Invite people in Team + +

+
+

Allowed email domains

+ {domains.length === 0 ? ( +

+ None: only people you invite can join. +

+ ) : ( +
    + {domains.map((d) => ( +
  • + {d} + +
  • + ))} +
+ )} +
+
+ { + setDomain(e.target.value); + setDomainError(""); + }} + /> + +
-
- { - setDomain(e.target.value); - setDomainError(""); - }} - /> - - -
- + + )}

- Require two-factor sign-in + {selfHosted ? "Require two-factor sign-in" : "Require two-factor sign-in for this team"}

{required ? `Required${data.require_2fa_since ? ` since ${new Date(data.require_2fa_since).toLocaleDateString()}` : ""}. People without it see a setup screen and nothing else.` : "Off: each person chooses for themselves in Settings, Security."}

+

+ + + {without === 0 + ? "Everyone has set it up." + : `${without} of ${people.length} ${people.length === 1 ? "person" : "people"} ${without === 1 ? "hasn't" : "haven't"} set it up yet.`} + +

Settings, Security - , then sign out and sign in again with your code. Then you can require it for everyone. + , then sign out and sign in again with your code. Then you can require it for {everyone}.

)}
@@ -335,6 +351,7 @@ function SignInSettingsPage() { {resetting && ( setResetting(null)} onDone={() => { toast(`Two-factor sign-in reset for ${who(resetting)}`); @@ -347,7 +364,17 @@ function SignInSettingsPage() { ); } -function ResetDialog({ person, onClose, onDone }: { person: Person; onClose: () => void; onDone: () => void }) { +function ResetDialog({ + person, + selfHosted, + onClose, + onDone, +}: { + person: Person; + selfHosted: boolean; + onClose: () => void; + onDone: () => void; +}) { const [how, setHow] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); @@ -378,7 +405,11 @@ function ResetDialog({ person, onClose, onDone }: { person: Person; onClose: () open onOpenChange={(o) => !o && onClose()} title={`Reset two-factor sign-in for ${who(person)}?`} - description="Only after you've checked it's really them, for example on a video call. Their next sign-in asks them to set it up again. This goes in the log under Settings, Roles." + description={ + selfHosted + ? "Only after you've checked it's really them, for example on a video call. Their next sign-in asks them to set it up again. This goes in the log under Settings, Roles." + : "Only after you've checked it's really them, for example on a video call. Their second factor is the same on every team they're on, so it's reset everywhere and they're signed out; they get an email saying so. This goes in the log under Settings, Roles." + } onSubmit={submit} testId="reset-2fa-dialog" footer={ diff --git a/dashboard/src/components/client-shell.tsx b/dashboard/src/components/client-shell.tsx index a2e5b0d6..98d674b7 100644 --- a/dashboard/src/components/client-shell.tsx +++ b/dashboard/src/components/client-shell.tsx @@ -4,7 +4,7 @@ import { can } from "@/lib/capabilities"; import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; import { type ReactNode, useEffect, useRef, useState } from "react"; -import { api, ApiError, type UsageInfo, type Banner, type TeamInfo } from "@/lib/api"; +import { api, ApiError, TWO_FACTOR_REQUIRED, type UsageInfo, type Banner, type TeamInfo } from "@/lib/api"; import { pushToDataLayer } from "@/lib/gtm"; import { BETA_SIGNUPS_CHANGED } from "@/lib/admin"; import { formatTokens, limitName, reachedLimit, USAGE_CHANGED, usageBreakdown, usageLimits } from "@/lib/usage"; @@ -156,13 +156,26 @@ export function ClientShell({ children }: { children: React.ReactNode }) { }); }; const [authChecked, setAuthChecked] = useState(false); - // A self-hosted install that requires two-factor sign-in: a session - // without a second factor sees only the setup screen. + // A team (a self-hosted install: the organization) that requires + // two-factor sign-in: a session without a second factor sees only the + // setup screen. A self-hosted install asks up front, as before; hosted + // learns it from the server's answer (`two_factor_required`) to the first + // request it holds, so a session that isn't held pays for no extra call. const [twoFactor, setTwoFactor] = useState(null); + const fetchTwoFactor = () => api.myTwoFactor().then(setTwoFactor, () => setTwoFactor(null)); const loadTwoFactor = () => { - if (!isSelfHosted()) return Promise.resolve(); - return api.myTwoFactor().then(setTwoFactor, () => setTwoFactor(null)); + if (isSelfHosted()) return fetchTwoFactor(); + return api.getUsage().then(setUsage, (e) => + e instanceof ApiError && e.code === "two_factor_required" ? fetchTwoFactor() : undefined, + ); }; + useEffect(() => { + const held = () => { + fetchTwoFactor(); + }; + window.addEventListener(TWO_FACTOR_REQUIRED, held); + return () => window.removeEventListener(TWO_FACTOR_REQUIRED, held); + }, []); // A self-hosted install's callback from Coderhelm's GitHub App or an OAuth // sign-in (lib/hybrid.ts): passed on before sign-in, since the person here // usually has no hosted account. @@ -251,7 +264,8 @@ export function ClientShell({ children }: { children: React.ReactNode }) { pushToDataLayer({ event: "identify", user_id: u.user_id, team_id: u.team_id }); await loadTwoFactor(); setAuthChecked(true); - api.getUsage().then(setUsage).catch(() => {}); + // Hosted read the usage already, on the way. + if (isSelfHosted()) api.getUsage().then(setUsage).catch(() => {}); api.getBanners().then((r) => setBanners(r.banners)).catch(() => {}); api.listTeams().then((r) => setTeams(r.teams)).catch(() => {}); }) @@ -323,7 +337,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) { await loadTwoFactor(); setUser(u); pushToDataLayer({ event: "identify", user_id: u.user_id, team_id: u.team_id }); - api.getUsage().then(setUsage).catch(() => {}); + if (isSelfHosted()) api.getUsage().then(setUsage).catch(() => {}); api.getBanners().then((r) => setBanners(r.banners)).catch(() => {}); api.listTeams().then((r) => setTeams(r.teams)).catch(() => {}); }} />; @@ -815,13 +829,15 @@ function SignInProblemNotice({ problem }: { problem: SignInProblem }) { } /** - * The organization requires two-factor sign-in and this session has none: - * set it up (or, when it is set up already, sign in again with the code). - * The server refuses everything else until then. + * The organization (hosted: the team this session acts in) requires + * two-factor sign-in and this session has none: set it up (or, when it is + * set up already, sign in again with the code). The server refuses + * everything else until then. */ function TwoFactorGate({ status, email, onDone }: { status: MyTwoFactor; email: string; onDone: () => void }) { const fits = status.fits ?? "cognito"; - const hasIt = status.set_up === fits; + const hasIt = !!status.set_up; + const who = status.self_hosted ? "Your organization" : "This team"; return (
@@ -834,8 +850,10 @@ function TwoFactorGate({ status, email, onDone }: { status: MyTwoFactor; email: {hasIt ? "Sign in again with your code" : "Set up two-factor sign-in"}

- Your organization requires two-factor sign-in. {hasIt - ? "You have it set up, but this session started without your code. Sign out, then sign in again and enter the code from your authenticator app." + {who} requires two-factor sign-in. {hasIt + ? status.set_up === "cognito" && fits === "app" + ? "Your code is on your password account. Sign out, then sign in with your email and password and enter the code from your authenticator app." + : "You have it set up, but this session started without your code. Sign out, then sign in again and enter the code from your authenticator app." : "Before you go on, set up an authenticator app: every sign-in will then ask for the 6-digit code it shows."}

{email &&

Signed in as {email}

} diff --git a/dashboard/src/components/settings-items.tsx b/dashboard/src/components/settings-items.tsx index 3cff1380..c4664780 100644 --- a/dashboard/src/components/settings-items.tsx +++ b/dashboard/src/components/settings-items.tsx @@ -52,7 +52,7 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [ label: "Team", items: [ { href: "/settings/team", title: "Team", description: "Who is on the team, their roles and what each role can do.", icon: , view: "view_team", edit: "people", status: "team" }, - { href: "/settings/sign-in", title: "Sign-in", description: "Who may join this install, and whether everyone must use two-factor sign-in.", icon: , view: "sign_in", edit: "sign_in", selfHosted: true }, + { href: "/settings/sign-in", title: "Sign-in", description: "Whether everyone must use two-factor sign-in, and who has it set up.", icon: , view: "sign_in", edit: "sign_in" }, { href: "/settings/support-access", title: "Support access", description: "Let Coderhelm support look at your workspace for a while, without changing anything. See every page they open.", icon: , view: "support", edit: "support" }, { href: "/settings/api-keys", title: "API keys", description: "Let your own scripts and tools use Coderhelm. For developers.", icon: , view: "api_keys", edit: "api_keys" }, ], diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index d1e0c478..42162287 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -51,12 +51,20 @@ export async function request(path: string, options?: RequestInit): Promise( return { ...(body as T), ok: true }; } -/** A person's own two-factor sign-in (self-hosted installs). */ +/** A person's own two-factor sign-in (both deployments). */ export interface MyTwoFactor { self_hosted: boolean; - /** The organization requires it. */ + /** The organization (hosted: the team this session acts in) requires it. */ required: boolean; /** This session can only set it up until it has a second factor. */ held: boolean; + /** A team they're on (or the organization) requires it, so it can't be turned off. */ + must_keep?: boolean; session_has_2fa?: boolean; signed_in_with?: "password" | "google" | "github"; /** What they have set up: Cognito's codes (password sign-in) or Coderhelm's (Google, GitHub). */ @@ -102,7 +112,7 @@ export interface MyTwoFactor { fits?: "cognito" | "app"; } -/** Settings, Sign-in (self-hosted installs). */ +/** Settings, Sign-in: the two-factor rule (hosted: this team's), and on a self-hosted install who may join. */ export interface SignInSettings { self_hosted: boolean; is_org?: boolean; @@ -119,6 +129,8 @@ export interface SignInSettings { two_factor: "cognito" | "app" | null; is_self: boolean; }[]; + /** How many people on the team have no second factor yet. */ + without_2fa?: number; api_keys?: { id: string; name: string; @@ -788,7 +800,7 @@ export const api = { }), mfaDisable: () => request<{ status: string }>("/api/users/mfa", { method: "DELETE" }), - // Self-hosted: one organization, who may join, and two-factor sign-in. + // Two-factor sign-in (both deployments); on a self-hosted install, who may join too. myTwoFactor: () => request("/api/users/2fa"), appTwoFactorSetup: () => request<{ secret: string; qr_uri: string }>("/api/users/2fa/app/setup", { method: "POST" }), @@ -800,7 +812,7 @@ export const api = { request<{ status: string; team_id: string }>("/auth/2fa/verify", { method: "POST", body: JSON.stringify({ code }) }), signInSettings: () => request("/api/sign-in"), updateSignInSettings: (body: { domains?: string[]; require_2fa?: boolean }) => - request<{ domains: string[]; require_2fa: boolean; require_2fa_since: string | null }>("/api/sign-in", { + request<{ domains: string[]; require_2fa: boolean; require_2fa_since: string | null; notified?: number }>("/api/sign-in", { method: "PUT", body: JSON.stringify(body), }), diff --git a/docs/content/docs/concepts/meta.json b/docs/content/docs/concepts/meta.json index 89a0b581..521dd532 100644 --- a/docs/content/docs/concepts/meta.json +++ b/docs/content/docs/concepts/meta.json @@ -1,4 +1,4 @@ { "title": "Concepts", - "pages": ["index", "agents", "agent-permissions", "skills", "memories", "code-graph", "data-sources", "aws-accounts", "test-fixes", "connections", "knowledge", "knowledge-sources", "chat", "roles", "token-limits", "usage-and-audit"] + "pages": ["index", "agents", "agent-permissions", "skills", "memories", "code-graph", "data-sources", "aws-accounts", "test-fixes", "connections", "knowledge", "knowledge-sources", "chat", "roles", "sign-in", "token-limits", "usage-and-audit"] } diff --git a/docs/content/docs/concepts/roles.mdx b/docs/content/docs/concepts/roles.mdx index d94a46f8..94313f5e 100644 --- a/docs/content/docs/concepts/roles.mdx +++ b/docs/content/docs/concepts/roles.mdx @@ -22,7 +22,7 @@ Every request to CoderHelm is checked in one place, on the server, against the c | --- | --- | | Viewer | `view`, `view_team`, `own_account` | | Member | `plans`, `runs`, `reviews`, `recommendations`, `view_alerts`, `view_integrations` | -| Admin | `people`, `roles`, `delete_plans`, `repos`, `agent_settings`, `memory`, `integrations`, `data_sources` (includes team tools and skills), `tests`, `alerts`, `model_provider`, `system`, `budget`, `support` | +| Admin | `people`, `roles`, `sign_in`, `delete_plans`, `repos`, `agent_settings`, `memory`, `integrations`, `data_sources` (includes team tools and skills), `tests`, `alerts`, `model_provider`, `system`, `budget`, `support` | | Owner | `manage_admins`, `team_name`, `disconnect` (removes Jira or the model key), `reset` | A request without the capability it needs gets `403`, with the name of the missing capability. @@ -49,4 +49,6 @@ Everyone else on the team can see the custom roles and what each one can do. A c Invites expire after 30 days; admins can resend them. +Admins can also require two-factor sign-in for the team (`sign_in`, never in a custom role); see [Sign-in and two-factor](/concepts/sign-in/). + Some actions need a second person, even an admin: approving a new version of a [team tool](/concepts/skills#team-tools) needs another admin when the team has more than one. diff --git a/docs/content/docs/concepts/sign-in.mdx b/docs/content/docs/concepts/sign-in.mdx new file mode 100644 index 00000000..92329d1e --- /dev/null +++ b/docs/content/docs/concepts/sign-in.mdx @@ -0,0 +1,47 @@ +--- +title: Sign-in and two-factor +description: How people sign in to CoderHelm, the one second factor each person has, and how a team's admins require two-factor sign-in. +--- + +People sign in to CoderHelm with an email and password, with Google, or with GitHub. All three lead to the same person (by email), on every team they are on. This page is about the hosted CoderHelm at app.coderhelm.com; a self-hosted install has its own [sign-in page](/self-host/sign-in/). + +## Your second factor + +Anyone can turn on two-factor sign-in for themselves in **Settings, Security**. Each person has **one** second factor, and CoderHelm asks for it however they sign in, whether or not a team requires it: + +- **People who sign in with a password** use the password account's own codes: the sign-in asks for a code from your authenticator app (any TOTP app: 1Password, Google Authenticator, Authy and so on) after your password. +- **People who sign in with Google or GitHub** don't pass through that step, so CoderHelm asks for its own authenticator-app code right after Google or GitHub. The secret is encrypted with AWS KMS. +- **A code set up after Google or GitHub** is asked for after a password sign-in too. +- **A code on the password account** can only be checked at the password sign-in: signing in with Google or GitHub sends you back to sign in with your email and password. +- **Neither kind can be set up while you have one.** To change it, turn the current one off first: the app code takes a current code to turn off, and the password account's code can be turned off only from a session that signed in with it. + +Your second factor is yours, not a team's: the same one is asked for on every team you are on. Turning it off ends your other sessions on every team. + +## Requiring it for a team + +A team's admins and owners can require two-factor sign-in for that team: **Settings, Sign-in, Require two-factor sign-in for this team**. + +- **Set it up for yourself first**, then sign out and sign in again with your code. The switch waits until your own session used a code, so you can't lock yourself out. +- **Settings, Sign-in shows how many people haven't set it up**, and who. When you turn it on, each of them gets an email with a link to set it up. +- **With it on, someone without a second factor in this session sees only a setup screen** in this team: they can set one up (if they have none), sign out, or read why. Nothing else in the team works until they finish. Sessions from before the switch are checked at their next request. The rule is read on every request. +- **The rule applies to the team you are acting in.** If you are on several teams, a team without the rule isn't held back by another team's rule. Your second factor stays on while any team you are on requires it. +- **API keys** are not people and keep working: a key never signs in. **Settings, Sign-in** and **Settings, API keys** mark each live key made before the rule was turned on, with whether the person who made it has a second factor now (or has left the team). Check those and revoke any you don't recognize. + +Turning the rule on or off goes in the log under **Settings, Roles**. + +## A lost phone + +If someone loses their phone, an admin resets their two-factor sign-in in **Settings, Sign-in** after checking it's really them (a video call, say). The admin writes how they checked; the reset and the reason go in the log under **Settings, Roles** before anything changes. + +- Their second factor is the same on every team, so it is reset everywhere, and their sessions on every team end. +- They get an email saying their two-factor sign-in was reset, so a reset they didn't ask for doesn't go unnoticed. +- They set it up again at their next sign-in (straight away, if a team they're on requires it). +- Only an owner can reset an admin's or another owner's. Nobody can reset their own. + +## Wrong codes + +Wrong codes count against the person, by email, across every way in. Ten wrong codes in 15 minutes pause sign-in with a code for 15 minutes; each pause after that is twice as long, up to a day, and the count starts over after a quiet day. One Google or GitHub sign-in allows five wrong codes before you start again from the sign-in screen. + +## Sessions that end + +Your existing sessions end when an admin resets your two-factor sign-in, removes you from the team or changes your role, and when you turn your own two-factor sign-in off (the session you did it from keeps working). diff --git a/docs/published-pages.json b/docs/published-pages.json index 37319cf8..2789b7d0 100644 --- a/docs/published-pages.json +++ b/docs/published-pages.json @@ -56,6 +56,7 @@ "/concepts/knowledge/", "/concepts/memories/", "/concepts/roles/", + "/concepts/sign-in/", "/concepts/skills/", "/concepts/test-fixes/", "/concepts/token-limits/", diff --git a/src/content/site.ts b/src/content/site.ts index 82a21621..e3f885d7 100644 --- a/src/content/site.ts +++ b/src/content/site.ts @@ -777,6 +777,7 @@ const security: Page = { { title: "Encrypted with AWS KMS", text: "Stored tokens, keys and connection details are encrypted with AWS KMS. Data source secrets carry your team in the encryption context, so they cannot be read for another team." }, { title: "Signed webhooks", text: "GitHub webhooks are checked with HMAC and SNS messages by signature before anything runs." }, { title: "Team scoped", text: "Every request is scoped to your team, and roles (owner, admin, billing, member, viewer) decide who can change what." }, + { title: "Two-factor sign-in", text: "Each person has one second factor, asked for after a password, Google or GitHub alike. A team's admins can require it: people without one see only a setup screen until they set it up." }, { title: "Read only data sources", text: "Database, API and log lookups are read only, enforced at several independent points.", href: "/data-sources/" }, ], },