diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 9813fc00a3..e80447ea41 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -601,6 +601,42 @@ have Full access. Files the server's user owns (`config.json`, the engine's environment) are also still readable from a bot's shell; that needs a second user for engines, a separate change. +## Sign in with a local password + +On a self-hosted server, an operator can set a password from the server's own interactive terminal: + +```sh +duskbot access add owner@example.com --password +duskbot access add member@example.com --chat-only --password +duskbot access password owner@example.com +``` + +The last command resets an existing allowed person's password without changing their role. +For Docker, run the same command with an interactive terminal as the server's user, for example +`docker compose exec dusk node dist-server/duskbot.js access password owner@example.com`. +Passwords are entered twice in a hidden prompt, never as command arguments. Use at least 12 +characters; passwords may be up to 1 KB in UTF-8, including spaces. There is no self-registration +or email reset. Shell access to the server is the owner's recovery path. + +Once a password is set, `/pair` offers email and password sign-in. Pairing and email codes +remain available. Password sign-in makes no request to dusk.bot or an email service. The +allow-list still controls access and roles, including environment-variable overrides. A +password reset revokes that address's existing local account sessions (including email-code +sessions) on the next membership check; removing its access does the same. Independently +paired devices remain managed through Remote access. Removing an individual with `duskbot access remove EMAIL` also deletes their password. +Editing the allow-list directly revokes access but retains the stored credential; reset it before +re-granting access if a new password is needed. + +In a signed-in browser, open the profile menu and choose **Sign out**. Confirming +ends only that browser's server session and returns to the sign-in page. Bots, +other signed-in browsers and connected AI providers keep running. The menu works +for password, email-code and paired browser sessions, including chat-only users. + +Only a random salt, scrypt hash and credential generation are saved in owner-readable files +(mode 0600) under `/passwords/`. Keep that directory private. Existing session expiry +and revocation apply. Passwords are available only on self-hosted servers, not desktop-managed +servers or dusk cloud. + ## Sign in with your email A pairing code is fine for the owner's own devices. For a workspace other diff --git a/docs/verification/README.md b/docs/verification/README.md index 9550e5b7d9..ec59dea273 100644 --- a/docs/verification/README.md +++ b/docs/verification/README.md @@ -336,6 +336,12 @@ sent mentions, multiline scrolling and responsive wrapping in real chat views. The [Group and Goal Local VM recipe](group-local-vm.md) checks per-speaker desktop routing, cancellation, and computer authority cleanup. +The [local password recipe](local-passwords.md) checks operator-managed credentials, +sign-in, revocation and browser sign-out in disposable fixtures. + +The [self-hosted interface recipe](self-hosted-interface.md) checks server-specific +copy, capability visibility and confirmed account-link status in both themes. + ## Evidence The [Gemini speech fixture](gemini-speech.md) checks write-only credentials, diff --git a/docs/verification/local-passwords.md b/docs/verification/local-passwords.md new file mode 100644 index 0000000000..3e3f686f69 --- /dev/null +++ b/docs/verification/local-passwords.md @@ -0,0 +1,46 @@ +# Local password sign-in + +Run the isolated credential, CLI and HTTP fixtures: + +```sh +pnpm exec vitest run server/passwords.test.ts server/cli-password.test.ts server/password-signin.test.ts server/email-signin.test.ts server/sessions.test.ts server/cli.test.ts +``` + +They verify private salted scrypt storage, equal hash work for unknown and wrong +credentials, password bounds, hidden CLI confirmation, live allow-list roles, +JSON-only requests, shared per-address lockout, secure cookies, password reset +revoking password and email sessions and SSE streams, revoked stream tickets, +access removal, pairing continuity, and the disabled-until-configured state. +The password branch can be verified independently of the self-hosted interface +changes; those changes are stacked on this branch for conflict-free review. +No test sends a real email or connects a real provider. + +For the real browser form: + +```sh +DUSK_UI_E2E=1 pnpm exec vitest run scripts/testing/password-signin.e2e.test.ts +``` + +This uses the verification launcher with a temporary home, the fake engine, +and a disposable browser profile. Set `AGENT_BROWSER_EXECUTABLE_PATH` to use +an existing test Chromium; otherwise the usual verification browser installer +is used. The test submits a wrong password and then the correct password through +the rendered form and verifies the resulting cookie session. It then signs out through the profile +menu and confirms the old cookie can no longer access the server. Light and dark +screenshots of password, email-code and pairing forms go to +`.dusk-scratch/password-signin/` (override with `DUSK_UI_EVIDENCE_DIR`). +`DUSK_AUTH_BASELINE=` captures the original pairing component at that +ref for comparison, with synthetic names and no personal data. All fixture +processes and data are removed on exit. This does not test a production upgrade. + +Browser sign-out is a related session-lifecycle follow-up: it calls the existing +logout endpoint through the existing confirmation dialog, revokes the browser +session and returns to sign-in. It does not add password or email editing, +sign-up, recovery mail, or another authentication mechanism. Password changes +and recovery remain operator CLI actions described in [self-hosting](../self-hosting.md). + +Run the sign-out and session component checks as well: + +```sh +pnpm exec vitest run src/components/ServerSignOut.dom.test.ts src/components/SidebarProfileMenu.test.ts src/lib/session.test.ts +``` diff --git a/docs/verification/self-hosted-interface.md b/docs/verification/self-hosted-interface.md new file mode 100644 index 0000000000..e6c08c54c8 --- /dev/null +++ b/docs/verification/self-hosted-interface.md @@ -0,0 +1,76 @@ +# Self-hosted interface + +The public environment descriptor identifies an operator-managed server by +`capabilities.selfUpdate === "operator"` without `cloudHome`. No configuration +switch is required. While the descriptor is unavailable, cloud offers stay +hidden; the client retries the lookup. + +The existing server sign-in page names the server and offers only enabled access +methods. Optional dusk bot accounts and AI provider connections are separate from +server access. A browser without a dusk bot account bridge does not offer account +sign-in or the hosted account dashboard. Self-hosted Usage & billing has no dusk +cloud offer or link. Desktop and dusk cloud keep their existing account flows. + +The related settings refinements use the same copy and capability boundary: + +- Computer names the current server (the hostname while loading) and hides + workspace setup that needs the desktop bridge. Advanced says "this server"; + functional server browser, pairing and access controls remain available. +- Phone keeps pairing and describes the bots on this server. +- Profile hides the profile email field on self-hosted instances because that + value does not change server credentials. Other profile fields remain editable. +- Updates hides Diagnostics when the desktop export bridge is unavailable. +- General hides Help improve dusk bot until the workspace has a confirmed dusk + account link. This is visibility only: it does not change consent, collected + data, session notes or the Shared data controls. + +The existing `GET /api/dashboard/link` response adds `accountLinked`. Enrollment +alone (`connected`) is insufficient: an unclaimed workspace has no account owner. +`accountLinked` uses the reporter's existing persisted `claimed` state. Enrollment +with no pending claim confirms ownership; a later report/wait response containing +an account-only `usageOptOut` boolean confirms completion of a pending claim. +Unlink, remote removal and a new pending enrollment do not keep the old account +status. Old records without confirmation remain hidden until confirmed, and the +UI hides the option when the field is missing or the request fails. No new +endpoint, persistence store, dependency, account flow or consent mechanism is +introduced. + +This UI branch is stacked on the local-password branch. Both pull requests target +`dev`; `main` is reserved for releases. Review the UI diff against the password +branch; land local passwords first, then rebase this branch onto updated `dev`. +This also keeps password changes out of the UI diff if the password change is +squash-merged. +Usage auto-refresh and self-service credential changes/recovery are outside this +change. + +Use isolated fixtures only, as described in [the verification guide](README.md). +Run the descriptor, menu, settings, pairing and account-status tests: + +```sh +pnpm exec vitest run src/lib/use-self-hosted.test.ts src/components/WorkspacesSettings.browser.test.ts src/components/SidebarProfileMenu.test.ts src/components/CloudUpsell.test.ts src/components/ProIntroduction.test.ts src/pair/PairPage.test.ts src/components/DataSharingRows.test.ts src/components/ProfileSettings.test.ts src/components/SettingsModal.grok.test.ts src/components/LocalComputerSection.dom.test.ts src/components/ServerPairingCard.elsewhere.test.ts src/components/WorkspacesGroup.dom.test.ts server/dashboard-reporter.test.ts server/routes/dashboard.test.ts +``` + +Capture the affected existing pages and menu in both themes: + +```sh +DUSK_UI_E2E=1 DUSK_SELF_HOSTED_CHECK=1 DUSK_SURFACES_ENDS=1 \ +DUSK_SURFACES_ONLY=settings:computer,settings:computer-advanced,settings:computer-computers,settings:computer-elsewhere,settings:general,settings:usage,settings:engines,settings:texting,settings:updates,small:account-menu \ +DUSK_SURFACES_SKINS=grok,grok-dark DUSK_SURFACES_VIEWPORTS=desktop \ +DUSK_GALLERY_DIR=.dusk-scratch/selfhost-after \ +pnpm exec vitest run scripts/testing/surface-gallery.e2e.test.ts +``` + +Capture Profile separately with `DUSK_SURFACES_ONLY=settings:profile`. The gallery's +About me textarea surface-style check also fails on the base revision; compare +the screenshots and email-field assertions separately from that baseline warning. +The password browser fixture in [local passwords](local-passwords.md) captures the +sign-in form and exercises browser sign-out. Run the gallery on the comparison +base without `DUSK_SELF_HOSTED_CHECK` for before images. Inspect each PNG and the +`opened` and layout results in `surfaces-report.json`; do not count a screenshot +alone as a working interaction. + +The fixtures use synthetic identities and a fake engine; no live account, +provider subscription or deployed server is used. Keep evidence local until +publication is authorized, then attach immutable before/after image links using +[the screenshot guidance](../brand-studio.md). No personal deployment data belongs +in the feature diff or public evidence. diff --git a/scripts/testing/password-signin-preview.tsx b/scripts/testing/password-signin-preview.tsx new file mode 100644 index 0000000000..eb65f8ef01 --- /dev/null +++ b/scripts/testing/password-signin-preview.tsx @@ -0,0 +1,13 @@ +import { createRoot } from "react-dom/client"; +import { PairPage } from "../../src/pair/PairPage"; +import { applySkin } from "../../src/lib/skins"; +import "../../src/font-faces.css"; +import "../../src/styles.css"; + +const params = new URLSearchParams(location.search); +applySkin(params.get("skin") === "light" ? "grok" : "grok-dark"); +const baselineModule = "/.dusk-scratch/PairPageBefore.tsx"; +const Component = params.has("baseline") + ? (await import(/* @vite-ignore */ baselineModule)).PairPage + : PairPage; +createRoot(document.getElementById("root")!).render(); diff --git a/scripts/testing/password-signin.e2e.test.ts b/scripts/testing/password-signin.e2e.test.ts new file mode 100644 index 0000000000..4d85dc27ce --- /dev/null +++ b/scripts/testing/password-signin.e2e.test.ts @@ -0,0 +1,95 @@ +import { execFileSync, spawn, type ChildProcess } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { expect, it } from "vitest"; +import { launchVerificationServer, type VerificationServer } from "../control-dusk.ts"; +import { fixtureApi, mountPreview, REPO_ROOT, type MountedPreview } from "./preview-fixture.ts"; +import { ensureUiBrowser } from "./control-dusk-ui.ts"; +import { connect } from "./chat-gallery/cdp.ts"; +import { PasswordStore } from "../../server/passwords.ts"; +import { waitForExit } from "../../server/testing/cleanup.ts"; + +it.skipIf(process.env.DUSK_UI_E2E !== "1")("signs in with a local password through the real page and captures its available methods", async () => { + let fixture: VerificationServer | undefined, preview: MountedPreview | undefined, chrome: ChildProcess | undefined; + let cdp: Awaited> | undefined; + const evidence = process.env.DUSK_UI_EVIDENCE_DIR || join(REPO_ROOT, ".dusk-scratch", "password-signin"); + const baselineFile = join(REPO_ROOT, ".dusk-scratch", "PairPageBefore.tsx"); + const baseline = process.env.DUSK_AUTH_BASELINE; + mkdirSync(evidence, { recursive: true }); + try { + if (baseline) { + const source = execFileSync("git", ["show", `${baseline}:src/pair/PairPage.tsx`], { cwd: REPO_ROOT, encoding: "utf8" }); + writeFileSync(baselineFile, source.replaceAll('"../', '"../src/')); + } + fixture = await launchVerificationServer(process.env); + await fixtureApi(fixture.info.url)("PATCH", "/api/config", { signIn: { admins: ["owner@example.test"] }, computerName: "Fixture server" }); + await new PasswordStore(fixture.info.dataDir).set("owner@example.test", "a fixture password"); + preview = await mountPreview(fixture, { entry: "/scripts/testing/password-signin-preview.tsx", route: "/__password.html", title: "Local sign-in fixture", hmr: false, logLevel: "warn", proxyHeaders: { host: "fixture.test", origin: "http://fixture.test", "x-forwarded-for": "203.0.113.7" }, extraRoutes: [{ path: "/.well-known/duskbot/environment", handler: async (_req, res) => { const descriptor = await (await fetch(fixture!.info.url + "/.well-known/duskbot/environment")).json(); res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ ...descriptor, label: "Fixture server" })); } }] }); + const profile = join(fixture.info.dataDir, "chrome"); mkdirSync(profile); + const browser = process.env.AGENT_BROWSER_EXECUTABLE_PATH || (await ensureUiBrowser()).chrome; + if (!browser) throw new Error("Set AGENT_BROWSER_EXECUTABLE_PATH to a test browser."); + chrome = spawn(browser, ["--headless=new", "--no-sandbox", "--no-first-run", "--disable-background-networking", "--password-store=basic", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "about:blank"], { env: { PATH: process.env.PATH, HOME: fixture.info.dataDir }, stdio: "ignore" }); + const portFile = join(profile, "DevToolsActivePort"); + await expect.poll(() => existsSync(portFile), { timeout: 30_000 }).toBe(true); + const [port, endpoint] = readFileSync(portFile, "utf8").trim().split("\n"); + cdp = await connect(`ws://127.0.0.1:${port}${endpoint}`); + const { targetId } = await cdp.request("Target.createTarget", { url: "about:blank" }); + const { sessionId } = await cdp.request("Target.attachToTarget", { targetId, flatten: true }); + const request = (method: string, params: unknown = {}) => cdp!.request(method, params, sessionId); + const evaluate = async (expression: string) => { + const answer = await request("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }); + if (answer.exceptionDetails) throw new Error(answer.exceptionDetails.text); + return answer.result.value; + }; + await request("Page.enable"); await request("Runtime.enable"); + await request("Emulation.setDeviceMetricsOverride", { width: 900, height: 800, deviceScaleFactor: 1, mobile: false }); + const click = (text: string) => evaluate(`Array.from(document.querySelectorAll('button')).find(b => b.textContent.trim() === ${JSON.stringify(text)})?.click()`); + const shot = async (name: string) => writeFileSync(join(evidence, `${baseline ? "before" : "after"}-${name}.png`), Buffer.from((await request("Page.captureScreenshot", { format: "png" })).data, "base64")); + for (const skin of ["light", "dark"]) { + await request("Page.navigate", { url: preview.previewUrl + `?skin=${skin}${baseline ? "&baseline=1" : ""}` }); + await expect.poll(() => evaluate(`!!document.querySelector('#signin-email')`), { timeout: 60_000 }).toBe(true); + await evaluate("document.fonts.ready"); + await shot(`${skin}-${baseline ? "email" : "password"}`); + if (!baseline) { + expect(await evaluate(`document.querySelector('#signin-password').type`)).toBe("password"); + await click("Use an email code instead"); + expect(await evaluate(`document.querySelector('#signin-password') === null`)).toBe(true); + await shot(`${skin}-email`); + } + await click("Have a pairing code instead?"); + await expect.poll(() => evaluate(`!!document.querySelector('#pair-code')`)).toBe(true); + await shot(`${skin}-pairing`); + } + if (!baseline) { + await click("Sign in with a password instead"); + const fill = (id: string, value: string) => evaluate(`(() => { const el = document.getElementById(${JSON.stringify(id)}); Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, ${JSON.stringify(value)}); el.dispatchEvent(new Event('input', { bubbles: true })); })()`); + await fill("signin-email", "owner@example.test"); await fill("signin-password", "the wrong password"); + await click("Sign in"); + await expect.poll(() => evaluate(`document.body.innerText.includes('email or password is incorrect')`)).toBe(true); + expect(await evaluate(`document.querySelector('#signin-password').value`)).toBe(""); + await fill("signin-password", "a fixture password"); await click("Sign in"); + await expect.poll(() => evaluate("location.pathname"), { timeout: 10_000 }).toBe("/"); + const session = await evaluate(`fetch('/api/auth/session').then(r => r.json())`); + expect(session).toMatchObject({ kind: "session", email: "owner@example.test", scopes: ["admin", "client"] }); + await request("Network.enable"); + const cookies = (await request("Network.getCookies", { urls: [preview.previewUrl] })).cookies; + const signedCookie = cookies.find((cookie: { httpOnly: boolean }) => cookie.httpOnly); + expect(signedCookie).toBeDefined(); + await expect.poll(() => evaluate("!!document.querySelector('button[aria-label=You]')"), { timeout: 60_000 }).toBe(true); + await click("Get started"); + await evaluate("document.querySelector('button[aria-label=You]').click()"); + await click("Sign out"); + await expect.poll(() => evaluate("document.body.innerText.includes('Sign out of this server?')")).toBe(true); + await evaluate("[...document.querySelectorAll('[role=alertdialog] button')].find(b=>b.textContent.trim()==='Sign out').click()"); + await expect.poll(() => evaluate("location.pathname"), { timeout: 10_000 }).toBe("/pair"); + expect([401, 403]).toContain(await evaluate("fetch('/api/config').then(r=>r.status)")); + const replay = await fetch(new URL("/api/auth/session", preview.previewUrl), { headers: { cookie: `${signedCookie.name}=${signedCookie.value}` } }); + expect([401, 403]).toContain(replay.status); + writeFileSync(join(evidence, "verified.json"), JSON.stringify({ passwordLogin: true, wrongPasswordRefused: true, cookieSession: session.kind, browserLogout: true, revokedCookieRefused: true, fixtureLog: fixture.info.logPath }, null, 2)); + } + } finally { + cdp?.close(); if (chrome && chrome.exitCode === null) { chrome.kill(); await waitForExit(chrome); } + await preview?.close(); await fixture?.close(); + if (baseline) rmSync(baselineFile, { force: true }); + } +}, 180_000); diff --git a/scripts/testing/surface-gallery.e2e.test.ts b/scripts/testing/surface-gallery.e2e.test.ts index 4763b28582..2675788896 100644 --- a/scripts/testing/surface-gallery.e2e.test.ts +++ b/scripts/testing/surface-gallery.e2e.test.ts @@ -121,7 +121,7 @@ const SMALL: Record ({ + id: `settings:computer-${page}`, + open: `{ type: "toggleAppSettings", open: true, section: "computer" }`, + scope: DIALOG_SCOPE, + run: `(async () => { + document.querySelector('[data-settings-block="advanced-fold"] button[aria-expanded="false"]')?.click(); + await new Promise(done => setTimeout(done, 300)); + if (${JSON.stringify(page)} !== "advanced") document.querySelector('[data-panel-page="${page}"]')?.click(); + return true; + })()`, + })), ...SETTINGS.map((section) => ({ id: `settings:${section}`, open: `{ type: "toggleAppSettings", open: true, section: "${section}" }`, scope: DIALOG_SCOPE })), ...PANEL.map((section) => ({ id: `panel:${section}`, open: `{ type: "toggleSettings", open: true, section: "${section}", botId: window.__surfaceGallery.botId }`, scope: DIALOG_SCOPE })), ...Object.entries(DIALOGS).map(([id, action]) => ({ id: `dialog:${id}`, open: action, scope: id === "computer" ? "#root" : DIALOG_SCOPE })), @@ -187,7 +199,13 @@ const SURFACES: Surface[] = [ await runControlDusk(["new-bot", "--name", "Pepper", "--url", fixture.info.url]); // one colour every run, so screenshots compare (scripts/testing/visual-baseline.ts); a new bot's colour is picked at random for (const one of (await api("GET", "/api/bots")).bots) await api("PATCH", `/api/bots/${one.id}`, { color: one.name === "Pepper" ? "orange" : "silver" }); - preview = await mountPreview(fixture, { entry: "/scripts/testing/surface-gallery-preview.tsx", route: "/__surface-gallery.html", title: "Surfaces gallery", logLevel: "warn", hmr: false }); + preview = await mountPreview(fixture, { entry: "/scripts/testing/surface-gallery-preview.tsx", route: "/__surface-gallery.html", title: "Surfaces gallery", logLevel: "warn", hmr: false, + ...(process.env.DUSK_SELF_HOSTED_CHECK === "1" ? { extraRoutes: [{ path: "/.well-known/duskbot/environment", handler: async (_req, res) => { + const environment = await (await fetch(fixture!.info.url + "/.well-known/duskbot/environment")).json(); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ ...environment, label: "Fixture server" })); + } }] } : {}), + }); if (SURFACES.some((surface) => surface.onboarding)) { fresh = await launchVerificationServer(process.env); await fixtureApi(fresh.info.url)("PATCH", "/api/config", { language: "en" }); @@ -278,6 +296,64 @@ const SURFACES: Surface[] = [ writeFileSync(join(evidence, `${shot}-end.png`), Buffer.from((await request("Page.captureScreenshot", { format: "png" })).data, "base64")); } } + if (process.env.DUSK_SELF_HOSTED_CHECK === "1") { + if (surface.id === "settings:profile") { + expect(await evaluate(`document.querySelector('input[aria-label="Email"]') === null`)).toBe(true); + } + if (surface.id === "settings:computer-advanced") { + expect(await evaluate(`document.body.innerText`)).toContain("Includes this server’s local network"); + } + if (surface.id === "settings:general") { + const privacy = await evaluate(`(() => ({ improve: !!document.querySelector('[data-help-improve]'), notes: !!document.querySelector('[data-session-notes]'), shared: !!document.querySelector('[data-panel-page="shared-data"]') }))()`); + expect(privacy).toEqual({ improve: false, notes: true, shared: true }); + } + expect(opened, surface.id).toBe(true); + const text = await evaluate(`document.body.innerText`); + if (surface.id === "settings:computer") { + const environment = await evaluate(`fetch('/.well-known/duskbot/environment').then(r => r.json())`); + expect(text).toContain(environment.label); + expect(text).toContain("Your bots run on this server."); + expect(await evaluate(`document.querySelector('[data-workspace="server"]') !== null`)).toBe(true); + expect(await evaluate(`document.querySelector('[data-settings-open="add-workspace"]') === null`)).toBe(true); + expect(text).not.toContain("This computer"); + } + if (surface.id === "settings:computer-computers") { + expect(text).toContain("This server"); + expect(text).toContain("Private desktop"); + expect(text).not.toContain("Your computer"); + expect(text).not.toContain("Add your own server"); + } + if (surface.id === "settings:computer-elsewhere") { + expect(text).toContain("This server's code"); + expect(text).toContain("Create code"); + expect(text).toContain("Access"); + expect(text).not.toContain("This computer's code"); + } + if (surface.id === "settings:texting") { + expect(text).toContain("dusk bot on your phone talks to the bots on this server."); + expect(text).toContain("iPhone"); + expect(text).toContain("Android"); + } + if (surface.id === "settings:updates") { + expect(text).not.toContain("Diagnostics"); + expect(text).toContain("Check for updates"); + } + if (surface.id === "settings:usage") { + expect(text).not.toContain("Optional managed hosting. This server is already self-hosted."); + expect(text).not.toContain("dusk cloud"); + expect(await evaluate(`document.querySelector('[data-cloud-offer]') === null`)).toBe(true); + } + if (surface.id === "settings:engines") { + expect(text).toContain("AI provider connections (optional)"); + expect(text).toContain("These accounts do not sign you into this server."); + } + if (surface.id === "small:account-menu") { + const menu = await evaluate(`document.querySelector('[role=menu]')?.textContent`); + expect(menu).toBeTruthy(); + expect(menu).not.toContain("Sign in"); + expect(menu).not.toContain("Account dashboard"); + } + } const probe = process.env.DUSK_GALLERY_PROBE ? await evaluate(process.env.DUSK_GALLERY_PROBE) : undefined; report.push({ shot, opened, issues, ...(probe === undefined ? {} : { probe }) }); } diff --git a/server/account-signin-routes.ts b/server/account-signin-routes.ts new file mode 100644 index 0000000000..7abc729543 --- /dev/null +++ b/server/account-signin-routes.ts @@ -0,0 +1,72 @@ +import type { IncomingMessage, ServerResponse } from "node:http"; +import type { EmailSignIn, SignInAllowList } from "./account-signin.ts"; +import { allowedScopes } from "./account-signin.ts"; +import { normalizeAccountEmail } from "../electron/control-plane-client.mjs"; +import { CLOUD_PERSONAL_REFUSAL } from "./cloud-owner.ts"; +import { json, readBody } from "./harness/http.ts"; +import { cookieMaxAgeSeconds, type SessionRegistry } from "./sessions.ts"; +import { labelFromUserAgent, requestOrigin, requestSource, serializeSessionCookie } from "./request-auth.ts"; +import type { PasswordStore } from "./passwords.ts"; +import type { EnvironmentDescriptor } from "./environment.ts"; + +export function createAccountSignInRoutes(deps: { + cloud: boolean; desktop: boolean; emailSignIn: EmailSignIn; passwords: PasswordStore; sessions: SessionRegistry; + allow: () => SignInAllowList; environment: () => EnvironmentDescriptor; cookieName: string; +}) { + const { emailSignIn, passwords, sessions } = deps; + let hashing = 0; + return async (req: IncomingMessage, res: ServerResponse, path: string, method: string): Promise => { + if (method !== "POST" || !["/api/auth/email/start", "/api/auth/email/verify", "/api/auth/password"].includes(path)) return false; + if (deps.cloud) { json(res, 403, { error: CLOUD_PERSONAL_REFUSAL, code: "cloud_personal" }); return true; } + if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) { + json(res, 415, { error: "send the sign-in request as JSON (content-type: application/json)" }); return true; + } + const password = path === "/api/auth/password"; + if (password ? deps.desktop || !passwords.enabled() : !emailSignIn.enabled()) { + json(res, 404, { error: "this sign-in method is not set up on this server; use a pairing code" }); return true; + } + const source = requestSource(req); + const allowed = sessions.attemptAllowed(source); + if (!allowed.ok) { json(res, 429, { error: `too many failed sign-in attempts from your address; try again in ${Math.ceil(allowed.retryAfterMs / 1000)}s` }); return true; } + if (password && hashing >= 4) { json(res, 429, { error: "sign-in is busy; try again in a moment" }); return true; } + const body = await readBody(req); + const email = typeof body?.email === "string" ? body.email : ""; + if (path === "/api/auth/email/start") { + const started = await emailSignIn.start(email); + if (!started.ok) { + if (started.status === 403) sessions.noteFailure(source); + json(res, started.status, { error: started.error }); + } else json(res, 200, { ok: true }); + return true; + } + const verified = await (async () => { + if (!password) return emailSignIn.verify(email, typeof body?.code === "string" ? body.code : ""); + if (hashing >= 4) return { ok: false as const, status: 429, error: "sign-in is busy; try again in a moment" }; + hashing += 1; + try { + const address = normalizeAccountEmail(email); + const version = await passwords.verify(address, typeof body?.password === "string" ? body.password : ""); + const scopes = allowedScopes(address, deps.allow()); + if (!version || !scopes || passwords.version(address) !== version) return { ok: false as const, status: 401, error: "email or password is incorrect" }; + return { ok: true as const, email: address, scopes, userId: undefined, passwordVersion: version }; + } finally { hashing -= 1; } + })(); + if (!verified.ok) { + if (verified.status === 401 || verified.status === 403) sessions.noteFailure(source); + json(res, verified.status, { error: verified.error }); return true; + } + // A reset during the asynchronous comparison must not grant a session with the new credential's generation. + if ("passwordVersion" in verified && passwords.version(verified.email) !== verified.passwordVersion) { + sessions.noteFailure(source); json(res, 401, { error: "email or password is incorrect" }); return true; + } + const scopes = allowedScopes(verified.email, deps.allow()); + if (!scopes) { sessions.noteFailure(source); json(res, 401, { error: "sign-in is no longer allowed" }); return true; } + sessions.clearFailures(source); + const label = typeof body?.label === "string" ? body.label : ""; + const issued = sessions.issue({ label: label.trim() || labelFromUserAgent(req.headers["user-agent"]), scopes, userId: verified.userId, email: verified.email, ...("passwordVersion" in verified ? { passwordVersion: verified.passwordVersion } : {}) }); + const secure = requestOrigin(req)?.startsWith("https://") === true; + res.setHeader("set-cookie", serializeSessionCookie(deps.cookieName, issued.token, { secure, maxAgeSeconds: cookieMaxAgeSeconds(issued.session) })); + json(res, 200, { session: issued.session, environment: deps.environment() }); + return true; + }; +} diff --git a/server/cli-access.ts b/server/cli-access.ts new file mode 100644 index 0000000000..59288a421f --- /dev/null +++ b/server/cli-access.ts @@ -0,0 +1,96 @@ +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { allowedScopes, parseAllowList } from "./account-signin.ts"; +import { appendAdminAction, flushAdminActivity, sharedSignIn } from "./admin-activity.ts"; +import { bindDecisionRetention, decisionRetentionDays } from "./decision-log.ts"; +import { writeFileAtomic } from "./atomic.ts"; +import { defaultSetupIo } from "./cli-prompts.ts"; +import { PasswordStore, passwordProblem } from "./passwords.ts"; +import { defaultIo, type CliIo, type CliOptions } from "./cli.ts"; + +const message = (error: unknown) => error instanceof Error ? error.message : String(error); + +/** Edits the sign-in allow-list in config.json, server live or stopped (read per request); DUSK_SIGNIN_EMAILS wins when set. */ +export async function runAccess(options: CliOptions, io: CliIo = defaultIo(), secret: (question: string) => Promise = (question) => defaultSetupIo().secret(question)): Promise { + const file = join(options.dataDir, "config.json"); + let raw: Record = {}; + if (existsSync(file)) { + try { + const parsed: unknown = JSON.parse(readFileSync(file, "utf8")); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object"); + raw = Object.fromEntries(Object.entries(parsed)); + } catch (error) { + io.error(`${file} could not be read (${message(error)}); fix it before changing who can sign in`); + return 1; + } + } + const current = typeof raw.signIn === "object" && raw.signIn !== null ? Object(raw.signIn) : {}; + const list = (value: unknown) => parseAllowList(Array.isArray(value) ? value.map(String).join(",") : ""); + const admins = list(Reflect.get(current, "admins")); + const members = list(Reflect.get(current, "members")); + const overridden = process.env.DUSK_SIGNIN_EMAILS !== undefined || process.env.DUSK_SIGNIN_MEMBER_EMAILS !== undefined; + const write = async (next: { admins: string[]; members: string[] }) => { + mkdirSync(options.dataDir, { recursive: true, mode: 0o700 }); + writeFileAtomic(file, `${JSON.stringify({ ...raw, signIn: next }, null, 2)}\n`, { mode: 0o600 }); + if (!sharedSignIn({ admins, members }) && !sharedSignIn(next)) return; + const decisions = raw.decisions && typeof raw.decisions === "object" ? (raw.decisions as { retentionDays?: unknown }).retentionDays : undefined; + bindDecisionRetention(() => decisionRetentionDays(typeof decisions === "number" ? decisions : undefined)); + const changed = (["admins", "members"] as const).filter((key) => next[key].join(",") !== (key === "admins" ? admins : members).join(",")); + appendAdminAction(options.dataDir, { + category: "people", action: "people.update", target: { kind: "settings" }, actor: { kind: "cli" }, + changed: changed.map((key) => `signIn.${key}`), + before: Object.fromEntries(changed.map((key) => [`signIn.${key}`, key === "admins" ? admins : members])), + after: Object.fromEntries(changed.map((key) => [`signIn.${key}`, next[key]])), + }); + await flushAdminActivity(options.dataDir); + }; + if (options.accessAction === "list") { + if (!admins.length && !members.length) { + io.log("nobody can sign in with an email yet; pairing codes only. Add someone with: duskbot access add you@example.com"); + return 0; + } + for (const entry of admins) io.log(`${entry.padEnd(40)} full access`); + for (const entry of members) io.log(`${entry.padEnd(40)} chat and approvals`); + if (overridden) io.log("(DUSK_SIGNIN_EMAILS / DUSK_SIGNIN_MEMBER_EMAILS are set in the environment and win over this list while the server runs)"); + return 0; + } + const entry = (options.email ?? "").trim().toLowerCase(); + if (!entry || (!entry.startsWith("@") && !entry.includes("@")) || /\s/.test(entry)) { + io.error("give an email address, or @domain for everyone at that domain"); + return 2; + } + if (options.password || options.accessAction === "password") { + const membership = { + admins: process.env.DUSK_SIGNIN_EMAILS === undefined ? admins : parseAllowList(process.env.DUSK_SIGNIN_EMAILS), + members: process.env.DUSK_SIGNIN_MEMBER_EMAILS === undefined ? members : parseAllowList(process.env.DUSK_SIGNIN_MEMBER_EMAILS), + }; + if (options.accessAction === "password" && !allowedScopes(entry, membership)) { + io.error("add this email to the sign-in list before setting a password"); + return 1; + } + if (entry.startsWith("@")) { io.error("give an individual email address for a password"); return 2; } + try { + const password = await secret("New password: "); + const problem = passwordProblem(password); + if (problem) throw new Error(problem); + if (password !== await secret("Confirm password: ")) throw new Error("passwords do not match"); + await new PasswordStore(options.dataDir).set(entry, password); + } catch (error) { io.error(message(error)); return 1; } + if (options.accessAction === "password") { io.log("Password changed; existing account sessions are revoked on their next check."); return 0; } + } + const without = (items: string[]) => items.filter((item) => item !== entry); + if (options.accessAction === "remove") { + if (!admins.includes(entry) && !members.includes(entry)) { + io.error(`${entry} is not on the list`); + return 1; + } + new PasswordStore(options.dataDir).remove(entry); + await write({ admins: without(admins), members: without(members) }); + io.log(`${entry} can no longer sign in (existing account sessions are revoked on their next check)`); + return 0; + } + await write(options.chatOnly ? { admins: without(admins), members: [...without(members), entry] } : { admins: [...without(admins), entry], members: without(members) }); + io.log(`${entry} can sign in at /pair with ${options.password ? "a password or emailed code" : "an emailed code"} (${options.chatOnly ? "chat and approvals" : "full access"})`); + if (overridden) io.log("note: DUSK_SIGNIN_EMAILS / DUSK_SIGNIN_MEMBER_EMAILS are set in the environment and win over this list while the server runs"); + return 0; +} diff --git a/server/cli-password.test.ts b/server/cli-password.test.ts new file mode 100644 index 0000000000..ec8b20dcf8 --- /dev/null +++ b/server/cli-password.test.ts @@ -0,0 +1,60 @@ +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { parseArgs, runAccess, type CliOptions } from "./cli.ts"; +import { PasswordStore } from "./passwords.ts"; +import { removeTempDir } from "./testing/cleanup.ts"; +const homes: string[] = []; +afterEach(async () => { vi.unstubAllEnvs(); await Promise.all(homes.splice(0).map(removeTempDir)); }); +const setup = () => { + const home = mkdtempSync(join(tmpdir(), "dusk-password-cli-")); homes.push(home); + const base = parseArgs(["access", "add", "owner@example.test", "--data-dir", home]) as CliOptions; + const io = { log: vi.fn(), error: vi.fn(), ask: vi.fn() }; + return { home, base, io, store: new PasswordStore(home) }; +}; +it("parses password commands without accepting a password as an argument", () => { + expect(parseArgs(["access", "add", "owner@example.test", "--password"])).toMatchObject({ password: true }); + expect(parseArgs(["access", "password", "owner@example.test"])).toMatchObject({ accessAction: "password" }); + expect(parseArgs(["access", "list", "--password"])).toHaveProperty("error"); + expect(parseArgs(["access", "password", "owner@example.test", "secret"])).toHaveProperty("error"); +}); +it("uses hidden confirmation, preserves roles on reset and does not log the secret", async () => { + const { home, base, io, store } = setup(); + const secret = vi.fn().mockResolvedValue("a fixture password"); + expect(await runAccess({ ...base, password: true, chatOnly: true }, io, secret)).toBe(0); + expect(secret).toHaveBeenCalledTimes(2); expect(io.ask).not.toHaveBeenCalled(); + const before = JSON.parse(readFileSync(join(home, "config.json"), "utf8")); + expect(before.signIn.members).toEqual(["owner@example.test"]); + expect(await store.verify("owner@example.test", "a fixture password")).not.toBeNull(); + secret.mockResolvedValue("the replacement password"); + expect(await runAccess({ ...base, accessAction: "password" }, io, secret)).toBe(0); + expect(JSON.parse(readFileSync(join(home, "config.json"), "utf8"))).toEqual(before); + expect(await store.verify("owner@example.test", "a fixture password")).toBeNull(); + expect(JSON.stringify(io.log.mock.calls)).not.toContain("fixture password"); +}); +it("cancel, mismatch and short input do not create credentials or grant access", async () => { + for (const secret of [vi.fn().mockRejectedValue(new Error("cancelled")), vi.fn().mockResolvedValue("short"), vi.fn().mockResolvedValueOnce("a fixture password").mockResolvedValueOnce("a different password")]) { + const { base, io, store } = setup(); + expect(await runAccess({ ...base, password: true }, io, secret)).toBe(1); + expect(store.enabled()).toBe(false); + } +}); +it("reset requires an allowed individual address and honors environment roles", async () => { + const { base, io, store } = setup(); const secret = vi.fn().mockResolvedValue("a fixture password"); + expect(await runAccess({ ...base, accessAction: "password" }, io, secret)).toBe(1); + expect(secret).not.toHaveBeenCalled(); + expect(await runAccess({ ...base, email: "@example.test", password: true }, io, secret)).toBe(2); + vi.stubEnv("DUSK_SIGNIN_MEMBER_EMAILS", "@example.test"); + expect(await runAccess({ ...base, accessAction: "password" }, io, secret)).toBe(0); + expect(store.enabled()).toBe(true); +}); + +it("removing an individual removes their password before access can be added again", async () => { + const { base, io, store } = setup(); + expect(await runAccess({ ...base, password: true }, io, vi.fn().mockResolvedValue("a fixture password"))).toBe(0); + expect(await runAccess({ ...base, accessAction: "remove" }, io)).toBe(0); + expect(store.enabled()).toBe(false); + expect(await runAccess(base, io)).toBe(0); + expect(await store.verify("owner@example.test", "a fixture password")).toBeNull(); +}); diff --git a/server/cli-usage.ts b/server/cli-usage.ts index 35078f88b1..42cfcbbca3 100644 --- a/server/cli-usage.ts +++ b/server/cli-usage.ts @@ -37,7 +37,7 @@ export const USAGE = `duskbot: your team of AI bots, ready in a few steps duskbot vps logs [--service server|link|fence] [--lines 100] [--json] duskbot login [--email you@example.com] duskbot logout - duskbot access list | add EMAIL [--chat-only] | remove EMAIL + duskbot access list | add EMAIL [--chat-only] [--password] | password EMAIL | remove EMAIL duskbot service install [--domain HOST | --tunnel | --tailscale] [--port N] [--data-dir DIR] | uninstall [--sentinel] (the health scan below, every two minutes, instead of the server) duskbot sentinel [--data-dir DIR] [--out DIR] [--once] [--json] (read-only health scan; see --help) @@ -79,6 +79,8 @@ login signs this machine in to a dusk bot account (an emailed code) logout releases that address and signs out access who may sign in with an emailed code at /pair: an address or @domain; --chat-only gives chat and approvals without settings. + --password sets a local password in a hidden terminal prompt. + access password EMAIL resets it; shell access is the recovery path. Takes effect at once, no restart. service keep the server running across reboots: writes a systemd unit (Linux) or a launchd agent (macOS) for the same serve options and diff --git a/server/cli.test.ts b/server/cli.test.ts index af9a81a1d8..462a007a71 100644 --- a/server/cli.test.ts +++ b/server/cli.test.ts @@ -66,7 +66,7 @@ describe("duskbot command line", () => { expect(parseArgs(["serve", "--tailscale", "--tunnel"], {})).toEqual({ error: "choose one of --tailscale (your tailnet) and --tunnel (a public address)" }); expect(parseArgs(["access", "add", "her@example.test", "--chat-only"], {})).toMatchObject({ command: "access", accessAction: "add", email: "her@example.test", chatOnly: true }); expect(parseArgs(["access", "list"], {})).toMatchObject({ command: "access", accessAction: "list" }); - expect(parseArgs(["access"], {})).toEqual({ error: "access needs one of: list, add EMAIL [--chat-only], remove EMAIL" }); + expect(parseArgs(["access"], {})).toEqual({ error: "access needs one of: list, add EMAIL [--chat-only] [--password], password EMAIL, remove EMAIL" }); expect(parseArgs(["access", "add"], {})).toEqual({ error: "add needs a value" }); expect(parseArgs(["service", "install", "--domain", "maus.example.com", "--port", "8799"], {})).toMatchObject({ command: "service", serviceAction: "install", domain: "maus.example.com", port: 8799 }); expect(parseArgs(["service", "uninstall"], {})).toMatchObject({ command: "service", serviceAction: "uninstall" }); @@ -420,6 +420,7 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => { const home = mkdtempSync(join(tmpdir(), "dusk-cli-tunnel-")); const dataDir = join(home, "data"); mkdirSync(dataDir, { recursive: true }); + writeFileSync(join(dataDir, "config.json"), JSON.stringify({ instances: { fixture: { driver: "cli-test-shadow" } } })); const stub = await startControlPlaneStub(); const fake = join(home, "cloudflared"); writeFileSync(fake, "#!/bin/sh\nexec sleep 300\n", { mode: 0o755 }); @@ -539,6 +540,7 @@ describe.skipIf(process.platform === "win32")("serve --domain", () => { const home = mkdtempSync(join(tmpdir(), "dusk-cli-domain-")); const dataDir = join(home, "data"); mkdirSync(dataDir, { recursive: true }); + writeFileSync(join(dataDir, "config.json"), JSON.stringify({ instances: { fixture: { driver: "cli-test-shadow" } } })); const fake = join(home, "fake-caddy"); writeFileSync(fake, `#!/bin/sh\necho "$@" > "${join(home, "caddy-args.txt")}"\necho $$ > "${join(home, "caddy.pid")}"\nexec sleep 300\n`, { mode: 0o755 }); const port = workerPort(21000, 9000); diff --git a/server/cli.ts b/server/cli.ts index 70cfcbdc5e..1c5e0322bb 100644 --- a/server/cli.ts +++ b/server/cli.ts @@ -7,12 +7,10 @@ import { dirname, join, resolve } from "node:path"; import { createInterface } from "node:readline/promises"; import { fileURLToPath } from "node:url"; -import { parseAllowList } from "./account-signin.ts"; -import { appendAdminAction, flushAdminActivity, sharedSignIn } from "./admin-activity.ts"; -import { bindDecisionRetention, decisionRetentionDays } from "./decision-log.ts"; +import { runAccess } from "./cli-access.ts"; +export { runAccess } from "./cli-access.ts"; import { resolveLoopbackTrust } from "./request-auth.ts"; import { restartPolicy } from "./restart.ts"; -import { writeFileAtomic } from "./atomic.ts"; import { ensureCaddy, normalizeDomainOption, startCaddy, type RunningCaddy } from "./caddy.ts"; import { runServiceCommand } from "./service-cli.ts"; import { runSentinelCli } from "./sentinel/cli.ts"; @@ -55,8 +53,9 @@ export interface CliOptions { client: boolean; pair: boolean; revoke?: string; - /** `access list|add|remove` */ - accessAction?: "list" | "add" | "remove"; + /** `access list|add|remove|password` */ + accessAction?: "list" | "add" | "remove" | "password"; + password?: boolean; chatOnly?: boolean; /** `service install|uninstall` */ serviceAction?: "install" | "uninstall"; @@ -129,10 +128,11 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): else if (arg === "--email") options.email = value(); else if (options.command === "sessions" && arg === "revoke") options.revoke = value(); else if (options.command === "push" && !options.pushAction && (arg === "test" || arg === "status")) options.pushAction = arg; - else if (options.command === "access" && !options.accessAction && (arg === "list" || arg === "add" || arg === "remove")) { + else if (options.command === "access" && !options.accessAction && (arg === "list" || arg === "add" || arg === "remove" || arg === "password")) { options.accessAction = arg; if (arg !== "list") options.email = value(); - } else if (options.command === "access" && arg === "--chat-only") options.chatOnly = true; + } else if (options.command === "access" && arg === "--password") options.password = true; + else if (options.command === "access" && arg === "--chat-only") options.chatOnly = true; else if (options.command === "service" && !options.serviceAction && (arg === "install" || arg === "uninstall")) options.serviceAction = arg; else if (options.command === "service" && arg === "--sentinel") options.sentinel = true; else if (options.command === "browser" && (arg === "install" || arg === "status" || arg === "setup")) options.browserAction = arg; @@ -145,7 +145,8 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65_535) return { error: "--port must be 1-65535" }; if (options.publicUrl && !/^https?:\/\//.test(options.publicUrl)) return { error: "--public-url must start with http:// or https://" }; if (options.tailscale && options.tunnel) return { error: "choose one of --tailscale (your tailnet) and --tunnel (a public address)" }; - if (options.command === "access" && !options.accessAction) return { error: "access needs one of: list, add EMAIL [--chat-only], remove EMAIL" }; + if (options.command === "access" && !options.accessAction) return { error: "access needs one of: list, add EMAIL [--chat-only] [--password], password EMAIL, remove EMAIL" }; + if (options.password && options.accessAction !== "add") return { error: "--password is only for access add EMAIL" }; if (options.command === "service" && !options.serviceAction) return { error: "service needs one of: install [the same options as serve], uninstall" }; if (options.domain && (options.tailscale || options.tunnel || options.publicUrl)) return { error: "--domain already gives the server its address; drop --tailscale, --tunnel and --public-url" }; if (options.local && (options.tailscale || options.tunnel || options.publicUrl)) return { error: "--local cannot be combined with a remote-access option" }; @@ -410,71 +411,6 @@ export async function runStatus(options: CliOptions, io: CliIo = defaultIo()): P return code; } -/** Edits the sign-in allow-list in config.json, server live or stopped (read per request); DUSK_SIGNIN_EMAILS wins when set. */ -export async function runAccess(options: CliOptions, io: CliIo = defaultIo()): Promise { - const file = join(options.dataDir, "config.json"); - let raw: Record = {}; - if (existsSync(file)) { - try { - const parsed: unknown = JSON.parse(readFileSync(file, "utf8")); - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object"); - raw = Object.fromEntries(Object.entries(parsed)); - } catch (error) { - io.error(`${file} could not be read (${message(error)}); fix it before changing who can sign in`); - return 1; - } - } - const current = typeof raw.signIn === "object" && raw.signIn !== null ? Object(raw.signIn) : {}; - const list = (value: unknown) => parseAllowList(Array.isArray(value) ? value.map(String).join(",") : ""); - const admins = list(Reflect.get(current, "admins")); - const members = list(Reflect.get(current, "members")); - const overridden = process.env.DUSK_SIGNIN_EMAILS !== undefined || process.env.DUSK_SIGNIN_MEMBER_EMAILS !== undefined; - const write = async (next: { admins: string[]; members: string[] }) => { - mkdirSync(options.dataDir, { recursive: true, mode: 0o700 }); - writeFileAtomic(file, `${JSON.stringify({ ...raw, signIn: next }, null, 2)}\n`, { mode: 0o600 }); - if (!sharedSignIn({ admins, members }) && !sharedSignIn(next)) return; - const decisions = raw.decisions && typeof raw.decisions === "object" ? (raw.decisions as { retentionDays?: unknown }).retentionDays : undefined; - bindDecisionRetention(() => decisionRetentionDays(typeof decisions === "number" ? decisions : undefined)); - const changed = (["admins", "members"] as const).filter((key) => next[key].join(",") !== (key === "admins" ? admins : members).join(",")); - appendAdminAction(options.dataDir, { - category: "people", action: "people.update", target: { kind: "settings" }, actor: { kind: "cli" }, - changed: changed.map((key) => `signIn.${key}`), - before: Object.fromEntries(changed.map((key) => [`signIn.${key}`, key === "admins" ? admins : members])), - after: Object.fromEntries(changed.map((key) => [`signIn.${key}`, next[key]])), - }); - await flushAdminActivity(options.dataDir); - }; - if (options.accessAction === "list") { - if (!admins.length && !members.length) { - io.log("nobody can sign in with an email yet; pairing codes only. Add someone with: duskbot access add you@example.com"); - return 0; - } - for (const entry of admins) io.log(`${entry.padEnd(40)} full access`); - for (const entry of members) io.log(`${entry.padEnd(40)} chat and approvals`); - if (overridden) io.log("(DUSK_SIGNIN_EMAILS / DUSK_SIGNIN_MEMBER_EMAILS are set in the environment and win over this list while the server runs)"); - return 0; - } - const entry = (options.email ?? "").trim().toLowerCase(); - if (!entry || (!entry.startsWith("@") && !entry.includes("@")) || /\s/.test(entry)) { - io.error("give an email address, or @domain for everyone at that domain"); - return 2; - } - const without = (items: string[]) => items.filter((item) => item !== entry); - if (options.accessAction === "remove") { - if (!admins.includes(entry) && !members.includes(entry)) { - io.error(`${entry} is not on the list`); - return 1; - } - await write({ admins: without(admins), members: without(members) }); - io.log(`${entry} can no longer sign in (existing sessions stay until they expire or are revoked with \`duskbot sessions revoke\`)`); - return 0; - } - await write(options.chatOnly ? { admins: without(admins), members: [...without(members), entry] } : { admins: [...without(admins), entry], members: without(members) }); - io.log(`${entry} can sign in at /pair with an emailed code (${options.chatOnly ? "chat and approvals" : "full access"})`); - if (overridden) io.log("note: DUSK_SIGNIN_EMAILS / DUSK_SIGNIN_MEMBER_EMAILS are set in the environment and win over this list while the server runs"); - return 0; -} - export async function runLogin(options: CliOptions, io: CliIo = defaultIo()): Promise { const account = createTunnelAccount({ dataDir: options.dataDir, version: serverVersion() }); const refusal = await loginRefusal(account); diff --git a/server/cloud-team-policy.ts b/server/cloud-team-policy.ts index a760b23284..d40a41ca3a 100644 --- a/server/cloud-team-policy.ts +++ b/server/cloud-team-policy.ts @@ -88,7 +88,7 @@ export function teamManagedPolicy(document: TeamPolicyDocument, team: Pick { async function fixture(prefix = "") { const dir = mkdtempSync(join(tmpdir(), "dashboard-reporter-")); dirs.push(dir); const reports: WorkspaceReport[] = [], signatures: boolean[] = [], enrollKeys: string[] = [], enrollTokens: unknown[] = [], enrollSignatures: (boolean | null)[] = []; - let publicKey = "", nextCommand: DashboardCommand | null = null, removed = false, unknown = 0, watching = false, waits = 0, hold = false; + let publicKey = "", nextCommand: DashboardCommand | null = null, removed = false, unknown = 0, watching = false, waits = 0, hold = false, claimed = true, accountAnswer = false; const server = createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(Buffer.from(chunk)); const bytes = Buffer.concat(chunks); @@ -44,7 +44,7 @@ async function fixture(prefix = "") { createPublicKey({ key: Buffer.from(publicKey, "base64"), format: "der", type: "spki" }), Buffer.from(String(signature), "base64"))); expect(body).toMatchObject({ v: 1, name: "Fixture", kind: "linux", version: "1" }); // a workspace the dashboard really removed comes back as a new one - reply(200, { v: 1, workspaceId: removed ? "workspace-new" : "workspace", claimUrl: `${base}/claim`, dashboardUrl: base, claimExpiresAt: removed ? 1 : 0 }); return; + reply(200, { v: 1, workspaceId: removed ? "workspace-new" : "workspace", claimUrl: `${base}/claim`, dashboardUrl: base, claimExpiresAt: removed || !claimed ? 1 : 0 }); return; } const time = Number(req.headers[SIGNATURE_HEADERS.time]); signatures.push(req.headers[SIGNATURE_HEADERS.workspace] === "workspace" && verify(null, @@ -55,17 +55,73 @@ async function fixture(prefix = "") { let commands: DashboardCommand[] = []; if (req.url === `${prefix}/v1/report`) reports.push(JSON.parse(bytes.toString())); if (req.url === `${prefix}/v1/wait?wait=25`) { waits++; if (hold) return; if (nextCommand) { commands = [nextCommand]; nextCommand = null; } } - reply(200, { v: 1, watching, nextReportMs: 600_000, commands }); + reply(200, { v: 1, watching, nextReportMs: 600_000, commands, ...(accountAnswer ? { usageOptOut: true } : {}) }); }); servers.push(server); await new Promise((ready) => server.listen(0, "127.0.0.1", ready)); const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}${prefix}`; const execute = vi.fn(async (command: DashboardCommand) => ({ id: command.id, ok: true, message: "Paused Morning brief.", at: Date.now() })); const make = (collect = collector(), pulse?: { since(after: number): Array<{ t: number; cpu: number; mem: number }> }, clock?: { now?: () => number; tickMs?: number; goneGraceMs?: number }) => { const reporter = createDashboardReporter({ dataDir: dir, collect, execute, pulse, ...clock }); reporters.push(reporter); return reporter; }; - return { dir, base, reports, signatures, enrollKeys, enrollTokens, enrollSignatures, execute, make, queue: (command: DashboardCommand) => { nextCommand = command; }, remove: () => { removed = true; }, forgetFor: (requests: number) => { unknown = requests; }, watch: () => { watching = true; }, waits: () => waits, hold: (on: boolean) => { hold = on; } }; + return { claim: (value: boolean) => { claimed = value; }, confirmAccount: () => { accountAnswer = true; }, dir, base, reports, signatures, enrollKeys, enrollTokens, enrollSignatures, execute, make, queue: (command: DashboardCommand) => { nextCommand = command; }, remove: () => { removed = true; }, forgetFor: (requests: number) => { unknown = requests; }, watch: () => { watching = true; }, waits: () => waits, hold: (on: boolean) => { hold = on; } }; } const command: DashboardCommand = { id: "command", kind: "routine.pause", target: "routine", issuedAt: Date.now(), expiresAt: Date.now() + 60_000 }; describe("dashboard reporter", () => { + it("distinguishes pending enrollment from an account, persists claim confirmation and clears it on unlink", async () => { + const f = await fixture(), reporter = f.make(); + expect(reporter.status().accountLinked).toBe(false); + f.claim(false); + await reporter.link(f.base); + await vi.waitFor(() => expect(f.reports.length).toBeGreaterThan(0)); + expect(reporter.status()).toMatchObject({ connected: true, accountLinked: false }); + f.confirmAccount(); + reporter.syncChoice(); + await vi.waitFor(() => expect(reporter.status().accountLinked).toBe(true)); + expect(JSON.parse(readFileSync(join(f.dir, "dashboard-link.json"), "utf8")).claimed).toBe(true); + reporter.stop(); + const restored = f.make(); + expect(restored.status().accountLinked).toBe(true); + await restored.forget(); + expect(restored.status()).toMatchObject({ connected: false, accountLinked: false }); + }); + + it("hides old unconfirmed records and resets claim status on a new enrollment", async () => { + const f = await fixture(), reporter = f.make(); + await reporter.link(f.base); + expect(reporter.status().accountLinked).toBe(true); + reporter.stop(); + const file = join(f.dir, "dashboard-link.json"); + const saved = JSON.parse(readFileSync(file, "utf8")); + delete saved.claimed; + writeFileSync(file, JSON.stringify(saved)); + const restored = f.make(); + expect(restored.status()).toMatchObject({ connected: true, accountLinked: false }); + f.claim(false); + await reporter.link(f.base); + expect(reporter.status()).toMatchObject({ connected: true, accountLinked: false }); + }); + + it("ignores account confirmation arriving after the link was forgotten", async () => { + const dir = mkdtempSync(join(tmpdir(), "dashboard-stale-")); dirs.push(dir); + let finishReport!: (response: Response) => void; + let finishWait!: (response: Response) => void; + const fetcher = vi.fn(async (input) => { + const url = String(input); + if (url.endsWith("/v1/enroll")) return Response.json({ v: 1, workspaceId: "workspace", claimUrl: "http://127.0.0.1/claim", dashboardUrl: "http://127.0.0.1", claimExpiresAt: 1 }); + if (url.endsWith("/v1/report")) return new Promise(resolve => { finishReport = resolve; }); + return new Promise(resolve => { finishWait = resolve; }); + }); + const reporter = createDashboardReporter({ dataDir: dir, collect: collector(), execute: vi.fn(), fetch: fetcher }); + reporters.push(reporter); + await reporter.link("http://127.0.0.1"); + await vi.waitFor(() => expect(finishReport).toBeTypeOf("function")); + await reporter.forget(); + const response = () => Response.json({ v: 1, watching: false, nextReportMs: 600_000, commands: [], usageOptOut: false }); + finishReport(response()); finishWait(response()); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(reporter.status()).toMatchObject({ connected: false, accountLinked: false }); + expect(existsSync(join(dir, "dashboard-link.json"))).toBe(false); + }); + it("reports apps at start and again after an app command, carrying the sign-in link", async () => { const f = await fixture(), collect = collector(); let services: Array<{ slug: string; connected: boolean; pending: boolean }> = []; @@ -93,7 +149,7 @@ describe("dashboard reporter", () => { it("enrolls, signs exact requests, executes a waited command and immediately delivers its result", async () => { const f = await fixture(), collect = collector(), activity = vi.spyOn(collect, "activity"), devices = vi.spyOn(collect, "devices"), plans = vi.spyOn(collect, "plans"); const reporter = f.make(collect); - expect(reporter.status().connected).toBe(false); reporter.start(); expect(f.reports).toHaveLength(0); + expect(reporter.status()).toMatchObject({ connected: false, accountLinked: false }); reporter.start(); expect(f.reports).toHaveLength(0); await reporter.link(f.base); await vi.waitFor(() => expect(f.reports.length).toBeGreaterThan(0)); f.queue(command); @@ -109,7 +165,7 @@ describe("dashboard reporter", () => { const saved = JSON.parse(readFileSync(file, "utf8")); expect(saved).toMatchObject({ v: 1, url: f.base, workspaceId: "workspace", claimed: true }); expect(createPublicKey({ key: Buffer.from(saved.publicKey, "base64"), format: "der", type: "spki" }).asymmetricKeyType).toBe("ed25519"); await reporter.link(f.base); expect(f.enrollKeys[1]).toBe(f.enrollKeys[0]); - await reporter.forget(); expect(existsSync(file)).toBe(false); expect(reporter.status().connected).toBe(false); + await reporter.forget(); expect(existsSync(file)).toBe(false); expect(reporter.status()).toMatchObject({ connected: false, accountLinked: false }); }); it("pushes immediately when watching starts and keeps seq increasing across recreated reporters", async () => { const f = await fixture(), first = f.make(); await first.link(f.base); @@ -148,7 +204,7 @@ describe("dashboard reporter", () => { await vi.waitFor(() => expect(f.reports).toHaveLength(1)); f.remove(); await vi.waitFor(() => expect(reporter.status().lastError).toBe("This workspace was removed from the dashboard. Connect it again from the app.")); const count = f.signatures.length; await new Promise((resolve) => setTimeout(resolve, 250)); - expect(f.signatures).toHaveLength(count); expect(reporter.status().connected).toBe(false); + expect(f.signatures).toHaveLength(count); expect(reporter.status()).toMatchObject({ connected: false, accountLinked: false }); reporter.start(); expect(f.signatures).toHaveLength(count); expect(existsSync(join(f.dir, "dashboard-link.json"))).toBe(true); expect(f.enrollKeys).toEqual([f.enrollKeys[0], f.enrollKeys[0]]); }); diff --git a/server/dashboard-reporter.ts b/server/dashboard-reporter.ts index fd6b9970c2..18b9e5f70d 100644 --- a/server/dashboard-reporter.ts +++ b/server/dashboard-reporter.ts @@ -138,6 +138,11 @@ export function createDashboardReporter(deps: DashboardReporterDeps) { } finally { clearTimeout(timeout); requests.delete(controller); } } function accept(answer: ReportAnswer, run: number) { + if (state && !state.claimed && typeof answer.usageOptOut === "boolean") { + const claimed = { ...state, claimed: true }; + save(claimed); + state = claimed; + } const beganWatching = !watching && answer.watching; watching = answer.watching; if (beganWatching) requestReport(); @@ -305,7 +310,7 @@ export function createDashboardReporter(deps: DashboardReporterDeps) { try { unlinkSync(file); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } } return { - status: () => ({ connected: state !== null && !removed, url: state?.url ?? null, workspaceId: state?.workspaceId ?? null, lastReportAt, lastError, watching }), + status: () => ({ connected: state !== null && !removed, accountLinked: state?.claimed === true && !removed, url: state?.url ?? null, workspaceId: state?.workspaceId ?? null, lastReportAt, lastError, watching }), link, forget, start, stop, /** the person changed the switch: tell the account now, not at the next report */ syncChoice: requestReport, diff --git a/server/environment.ts b/server/environment.ts index 2cf343835d..6131ace57c 100644 --- a/server/environment.ts +++ b/server/environment.ts @@ -46,6 +46,8 @@ export interface EnvironmentDescriptor { selfUpdate: "desktop-managed" | "operator"; /** Whether /pair offers "sign in with your email" (an allow-list is set). */ emailSignIn?: boolean; + /** Local password sign-in is configured by the server operator. */ + passwordSignIn?: boolean; /** GET /api/threads/:id/job answers, long-polled (the headless CLI needs it). */ jobs: true; }; @@ -135,7 +137,7 @@ export function serverVersion(root = SERVER_ROOT): string { return "unknown"; } -export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor { +export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; passwordSignIn?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor { return { environmentId: input.environmentId, label: input.label?.trim() || process.env.DUSK_ENVIRONMENT_LABEL?.trim() || hostname(), @@ -151,6 +153,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan ...(input.cloudHome === true && input.cloudTeam === true ? { cloudTeam: true as const } : {}), selfUpdate: input.desktopManaged ? "desktop-managed" : "operator", emailSignIn: input.emailSignIn === true, + ...(input.passwordSignIn === true ? { passwordSignIn: true } : {}), jobs: true, }, }; diff --git a/server/index.ts b/server/index.ts index 224918a35a..5de2cde372 100644 --- a/server/index.ts +++ b/server/index.ts @@ -553,6 +553,8 @@ import { createWorkspaceBackupRoutes, tracksWorkspaceRequest } from "./workspace import { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRestoreResult } from "./workspace-backup.ts"; import { repairMovedWorkspacePaths } from "./moved-paths-repair.ts"; import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } from "./custom-domain.ts"; +import { PasswordStore } from "./passwords.ts"; +import { createAccountSignInRoutes } from "./account-signin-routes.ts"; import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-signin.ts"; import { ProviderAuthSessions } from "./provider-auth-sessions.ts"; import { @@ -710,7 +712,9 @@ const signInAllowList = cacheUntilConfigChanges((config) => ({ admins: parseAllowList(config.signIn?.admins?.join(",")), members: parseAllowList(config.signIn?.members?.join(",")), })); +const passwords = new PasswordStore(DATA_DIR); const sessions = new SessionRegistry({ + passwordVersion: (email) => passwords.version(email), file: join(DATA_DIR, "sessions.json"), emailScopesSnapshot: () => { const membership = signInAllowList(); @@ -800,6 +804,10 @@ const customDomainVerifier = createCustomDomainVerifier({ environmentId: ENVIRON const emailSignIn = createEmailSignIn({ allow: signInAllowList, version: serverVersion(), }); +const accountSignInRoutes = createAccountSignInRoutes({ + cloud: Boolean(CLOUD_HOME), desktop: DESKTOP_MANAGED, emailSignIn, passwords, sessions, allow: signInAllowList, cookieName: SESSION_COOKIE, + environment: () => environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: emailSignIn.enabled(), passwordSignIn: !DESKTOP_MANAGED && passwords.enabled() }), +}); let customDomainRevision = 0; function savedCustomDomain(): string | null { if (DESKTOP_MANAGED || !cfg.customDomain) return null; @@ -13821,7 +13829,7 @@ const handleRequestInner = async (req: IncomingMessage, res: ServerResponse) => // Two public routes come first; everything else needs the loopback owner or a paired session with the right scope. if (method === "GET" && !path.startsWith("/api/") && !path.startsWith("/.well-known/") && (moveFreeze.screen(path) ? (res.writeHead(302, { location: moveFreeze.screen(path)!, "cache-control": "no-store" }).end(), true) : serveStatic(res, path, STATIC_DIR, req))) return; if (method === "GET" && path === "/.well-known/duskbot/environment") { - return json(res, 200, { ...environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }), sealIdentity: sealer.identity(), link: linkProtocolInfo() }); + return json(res, 200, { ...environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), passwordSignIn: !CLOUD_HOME && !DESKTOP_MANAGED && passwords.enabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }), sealIdentity: sealer.identity(), link: linkProtocolInfo() }); } const domainCheck = /^\/\.well-known\/duskbot\/domain-check\/([a-f0-9]{64})$/.exec(path); if (method === "GET" && domainCheck) { @@ -13829,43 +13837,7 @@ const handleRequestInner = async (req: IncomingMessage, res: ServerResponse) => const challenge = customDomainVerifier.challenge(domainCheck[1]); return json(res, challenge ? 200 : 404, challenge ?? { error: "No active domain check." }); } - // Never on a Cloud home: it is personal, and the owner's devices sign in through the Admin. - if (CLOUD_HOME && method === "POST" && (path === "/api/auth/email/start" || path === "/api/auth/email/verify")) { - return json(res, 403, { error: CLOUD_PERSONAL_REFUSAL, code: "cloud_personal" }); - } - if (method === "POST" && (path === "/api/auth/email/start" || path === "/api/auth/email/verify")) { - if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) { - return json(res, 415, { error: "send the sign-in request as JSON (content-type: application/json)" }); - } - if (!emailSignIn.enabled()) return json(res, 404, { error: "email sign-in is not set up on this server; use a pairing code" }); - const source = requestSource(req); - const allowed = sessions.attemptAllowed(source); - if (!allowed.ok) return json(res, 429, { error: `too many failed sign-in attempts from your address; try again in ${Math.ceil(allowed.retryAfterMs / 1000)}s` }); - const body = await readBody(req); - const email = typeof body?.email === "string" ? body.email : ""; - if (path === "/api/auth/email/start") { - const started = await emailSignIn.start(email); - if (!started.ok) { - if (started.status === 403) sessions.noteFailure(source); - return json(res, started.status, { error: started.error }); - } - return json(res, 200, { ok: true }); - } - const code = typeof body?.code === "string" ? body.code : ""; - const label = typeof body?.label === "string" ? body.label : ""; - const verified = await emailSignIn.verify(email, code); - if (!verified.ok) { - if (verified.status === 401 || verified.status === 403) sessions.noteFailure(source); - console.warn(`email sign-in refused from ${source}: ${verified.error}`); - return json(res, verified.status, { error: verified.error }); - } - sessions.clearFailures(source); - const issued = sessions.issue({ label: label.trim() || labelFromUserAgent(req.headers["user-agent"]), scopes: verified.scopes, userId: verified.userId, email: verified.email }); - const environment = environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: true }); - const secure = requestOrigin(req)?.startsWith("https://") === true; - res.setHeader("set-cookie", serializeSessionCookie(SESSION_COOKIE, issued.token, { secure, maxAgeSeconds: cookieMaxAgeSeconds(issued.session) })); - return json(res, 200, { session: issued.session, environment }); - } + if (await accountSignInRoutes(req, res, path, method)) return; if ((cloudSigned && await cloudSigned({ req, res, url, path, method })) || chatApps.serveFile(req, res, path, method)) return; if (method === "POST" && path === "/api/auth/pair") { // JSON only: a cross-site HTML form cannot send this content type without a preflight, so no unused code is planted as a session. @@ -13891,7 +13863,7 @@ const handleRequestInner = async (req: IncomingMessage, res: ServerResponse) => return json(res, result.status, { error: result.error }); } if (CLOUD_TEAM) teamHost.met(result.session); - const environment = environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }); + const environment = environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: !CLOUD_HOME && emailSignIn.enabled(), passwordSignIn: !CLOUD_HOME && !DESKTOP_MANAGED && passwords.enabled(), cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, ownHome: ownHome.takesMove() }); if (wantsCookie) { const previous = browser ? sessions.authenticate(parseCookies(req.headers.cookie).get(SESSION_COOKIE)) : null; if (previous && previous.id !== result.session.id) sessions.revoke(previous.id); diff --git a/server/password-signin.test.ts b/server/password-signin.test.ts new file mode 100644 index 0000000000..89fd2085ad --- /dev/null +++ b/server/password-signin.test.ts @@ -0,0 +1,227 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { request as httpRequest } from "node:http"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { removeTempDir, waitForExit } from "./testing/cleanup.ts"; +import { startControlPlaneStub, type ControlPlaneStub } from "./testing/control-plane-stub.ts"; +import { PasswordStore } from "./passwords.ts"; +import { openSse } from "./testing/sse.ts"; +import { workerPort } from "./testing/worker-port.ts"; + +const SERVER_DIR = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(SERVER_DIR, ".."); +const PORT = workerPort(34000, 5000); +const HOST = "agentada.test"; + +let home: string; +let child: ChildProcess; +let stub: ControlPlaneStub; +let stderr = ""; + +interface Reply { + status: number; + headers: Record; + body: any; +} + +/** A remote browser: a foreign Host and a forwarded address, like a proxy or tunnel hands us. */ +function call(path: string, init: { method?: string; body?: unknown; headers?: Record; from?: string } = {}): Promise { + return new Promise((resolve, reject) => { + const payload = init.body === undefined ? undefined : JSON.stringify(init.body); + const req = httpRequest( + { + hostname: "127.0.0.1", + port: PORT, + path, + method: init.method ?? (payload ? "POST" : "GET"), + headers: { + host: HOST, + "x-forwarded-for": init.from ?? "203.0.113.7", + "x-forwarded-proto": "https", + ...(payload ? { "content-type": "application/json" } : {}), + ...init.headers, + }, + }, + (res) => { + let raw = ""; + res.on("data", (chunk) => (raw += chunk)); + res.on("end", () => { + let body: unknown = raw; + try { + body = JSON.parse(raw); + } catch { + } + resolve({ status: res.statusCode ?? 0, headers: res.headers, body }); + }); + }, + ); + req.on("error", reject); + if (payload) req.write(payload); + req.end(); + }); +} + +const cookieOf = (reply: Reply): string => { + const raw = reply.headers["set-cookie"]; + const first = Array.isArray(raw) ? raw[0] : raw; + return (first ?? "").split(";")[0]; +}; + +async function signIn(email: string): Promise { + expect((await call("/api/auth/email/start", { body: { email } })).status).toBe(200); + const reply = await call("/api/auth/email/verify", { body: { email, code: stub.otp } }); + expect(reply.status).toBe(200); + return cookieOf(reply); +} + +async function openEvents(cookie: string) { + const stream = await openSse(`http://127.0.0.1:${PORT}/api/events`, { + "x-forwarded-for": "203.0.113.7", "x-forwarded-proto": "https", cookie, + }); + await stream.until((frame) => frame.kind === "hello"); + return stream; +} + +beforeAll(async () => { + stub = await startControlPlaneStub(); + home = mkdtempSync(join(tmpdir(), "dusk-email-signin-")); + const staticDir = join(home, "static"); + mkdirSync(join(home, ".duskbot"), { recursive: true }); + mkdirSync(join(staticDir, "assets"), { recursive: true }); + writeFileSync(join(staticDir, "index.html"), "Served UI"); + writeFileSync(join(home, ".duskbot", "config.json"), JSON.stringify({ + instances: { fixture: { driver: "email-signin-test-shadow" } }, + signIn: { admins: ["her@example.test", "@agentada.test"], members: ["staff@example.test"] }, + })); + const passwords = new PasswordStore(join(home, ".duskbot")); + await passwords.set("her@example.test", "a fixture password"); + await passwords.set("staff@example.test", "a fixture password"); + await passwords.set("removed@example.test", "a fixture password"); + child = spawn(process.execPath, [join(SERVER_DIR, "index.ts")], { + cwd: ROOT, + env: { + ...(process.env.PATH ? { PATH: process.env.PATH } : {}), + ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), + HOME: home, + USERPROFILE: home, + DUSK_PORT: String(PORT), + DUSK_WEBHOOK_PORT: String(PORT + 1), + DUSK_STATIC_DIR: staticDir, + DUSK_PUBLIC_URL: `https://${HOST}`, + DUSK_ENVIRONMENT_LABEL: "agentada", + DUSK_BROWSER_CONNECTION: join(home, "browser-test-connection.json"), + DUSK_CONTROL_PLANE_URL: stub.url, + DUSK_LOOPBACK_TRUST: "service", + DUSK_SSE_HEARTBEAT_MS: "50", + }, + stdio: ["ignore", "pipe", "pipe"], + }); + child.stderr?.on("data", (chunk) => (stderr += String(chunk))); + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + try { + const res = await fetch(`http://127.0.0.1:${PORT}/api/health`); + if (res.ok) return; + } catch { + } + await new Promise((r) => setTimeout(r, 100)); + } + throw new Error(`server did not start:\n${stderr}`); +}, 30_000); + +afterAll(async () => { + await waitForExit(child, { signal: "SIGTERM" }); + await stub.close(); + await removeTempDir(home); +}); + + +const login = (email = "her@example.test", password = "a fixture password", from?: string) => call("/api/auth/password", { body: { email, password, label: "Fixture browser" }, from }); + +describe("local password sign-in on a real isolated server", () => { + it("advertises passwords and issues a secure local admin session without contacting the email service", async () => { + expect((await call("/.well-known/duskbot/environment")).body.capabilities.passwordSignIn).toBe(true); + const right = await login("HER@EXAMPLE.TEST"); + expect(right.status).toBe(200); + expect(right.body.session).toMatchObject({ email: "her@example.test", scopes: ["admin", "client"] }); + expect(String(right.headers["set-cookie"])).toMatch(/HttpOnly/); + expect(String(right.headers["set-cookie"])).toMatch(/Secure/); + expect(String(right.headers["set-cookie"])).toMatch(/SameSite=Lax/); + expect(JSON.stringify(right.body)).not.toMatch(/passwordVersion|salt|hash|fixture password/); + const config = await call("/api/config", { headers: { cookie: cookieOf(right) } }); + expect(config.status).toBe(200); + expect(stub.calls).toHaveLength(0); + }); + + it("uses identical refusals for wrong, unknown and disallowed credentials, and rejects form posts", async () => { + const wrong = await login("her@example.test", "the wrong password"); + const unknown = await login("unknown@example.test"); + const removed = await login("removed@example.test"); + expect(wrong.status).toBe(401); + expect(unknown.body).toEqual(wrong.body); expect(removed.body).toEqual(wrong.body); + expect(cookieOf(wrong)).toBe(""); + const form = await call("/api/auth/password", { body: { email: "her@example.test", password: "a fixture password" }, headers: { "content-type": "text/plain" } }); + expect(form.status).toBe(415); + }); + + it("members keep chat-only access and share lockout with pairing and email methods", async () => { + const member = await login("staff@example.test"); + expect(member.body.session.scopes).toEqual(["client"]); + expect((await call("/api/config", { method: "PUT", body: { language: "en" }, headers: { cookie: cookieOf(member) } })).status).toBe(403); + let last = 0; + for (let i = 0; i < 12; i++) { last = (await login("unknown@example.test", "a wrong password", "198.51.100.42")).status; if (last === 429) break; } + expect(last).toBe(429); + expect((await login("her@example.test", "a fixture password", "198.51.100.42")).status).toBe(429); + expect((await call("/api/auth/email/start", { body: { email: "her@example.test" }, from: "198.51.100.42" })).status).toBe(429); + expect((await call("/api/auth/pair", { body: { code: "BAD-CODE" }, from: "198.51.100.42" })).status).toBe(429); + expect((await login("her@example.test", "a fixture password", "198.51.100.43")).status).toBe(200); + }); + + it("reset ends password and email sessions, live streams and stream tickets; pairing remains available", async () => { + const first = await login(); const cookie = cookieOf(first); + const emailCookie = await signIn("her@example.test"); + const stream = await openEvents(cookie); + try { + const ticket = await call("/api/auth/stream-ticket", { body: {}, headers: { cookie } }); + expect(ticket.status).toBe(200); + const pairing = await call("/api/auth/pairing", { body: {}, headers: { cookie } }); + const paired = await call("/api/auth/pair", { body: { code: pairing.body.code, cookie: true } }); + expect(paired.status).toBe(200); + await new PasswordStore(join(home, ".duskbot")).set("her@example.test", "the replacement password"); + await expect(stream.until(() => false, 2_500)).rejects.toThrow("SSE stream closed"); + expect((await call("/api/bots", { headers: { cookie } })).status).toBe(401); + expect((await call("/api/bots", { headers: { cookie: emailCookie } })).status).toBe(401); + expect((await call(`/api/events?ticket=${ticket.body.ticket}`)).status).toBe(401); + expect((await call("/api/bots", { headers: { cookie: cookieOf(paired) } })).status).toBe(200); + expect((await login()).status).toBe(401); + expect((await login("her@example.test", "the replacement password")).status).toBe(200); + } finally { stream.close(); } + }); + + it("removing access revokes sessions and restoring access does not revive their cookies", async () => { + const member = cookieOf(await login("staff@example.test")); + const stream = await openEvents(member); + const file = join(home, ".duskbot", "config.json"); + const config = JSON.parse(readFileSync(file, "utf8")); + try { + writeFileSync(file, JSON.stringify({ ...config, signIn: { ...config.signIn, members: [] } })); + await expect(stream.until(() => false, 2500)).rejects.toThrow("SSE stream closed"); + expect((await login("staff@example.test")).status).toBe(401); + writeFileSync(file, JSON.stringify(config)); + expect((await call("/api/bots", { headers: { cookie: member } })).status).toBe(401); + } finally { stream.close(); writeFileSync(file, JSON.stringify(config)); } + }); + it("does not offer password login when no local passwords are configured", async () => { + const directory = join(home, ".duskbot", "passwords"); + renameSync(directory, directory + "-held"); + try { + expect((await call("/.well-known/duskbot/environment")).body.capabilities.passwordSignIn).toBeUndefined(); + expect((await login()).status).toBe(404); + } finally { renameSync(directory + "-held", directory); } + }); + +}); diff --git a/server/passwords.test.ts b/server/passwords.test.ts new file mode 100644 index 0000000000..dc764f16bd --- /dev/null +++ b/server/passwords.test.ts @@ -0,0 +1,94 @@ +import { mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { removeTempDir } from "./testing/cleanup.ts"; + +vi.mock("node:crypto", async original => { + const actual = await original(); + return { ...actual, scrypt: vi.fn(actual.scrypt), timingSafeEqual: vi.fn(actual.timingSafeEqual) }; +}); +import { scrypt, timingSafeEqual } from "node:crypto"; +import { PasswordStore, passwordProblem } from "./passwords.ts"; +import { SessionRegistry } from "./sessions.ts"; +import { excludedWorkspaceAuthPath } from "./workspace-backup-policy.ts"; + +const homes: string[] = []; +const fixture = () => { const dir = mkdtempSync(join(tmpdir(), "dusk-password-")); homes.push(dir); return { dir, store: new PasswordStore(dir) }; }; +const password = "a long test password"; +afterEach(async () => { vi.clearAllMocks(); await Promise.all(homes.splice(0).map(removeTempDir)); }); + +it("keeps salted hashes private, survives reopening, and does not export credentials with the workspace", async () => { + const { dir, store } = fixture(); + expect(store.enabled()).toBe(false); + await store.set("OWNER@example.test", password); + await store.set("member@example.test", password); + expect(store.enabled()).toBe(true); + const records = readdirSync(join(dir, "passwords")).map(name => { + const file = join(dir, "passwords", name); + if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); + const raw = readFileSync(file, "utf8"); + expect(raw).not.toContain(password); expect(raw).not.toContain("example.test"); + expect(excludedWorkspaceAuthPath(`passwords/${name}`)).toBe(true); + return JSON.parse(raw); + }); + expect(records[0].salt).not.toBe(records[1].salt); + expect(records[0].hash).not.toBe(records[1].hash); + expect(records[0].salt).toHaveLength(32); expect(records[0].hash).toHaveLength(128); + expect(await new PasswordStore(dir).verify("owner@example.test", password)).toBe(store.version("owner@example.test")); +}); + +it("uses the same hash work and constant-time comparison for wrong, unknown and malformed credentials", async () => { + const { store } = fixture(); await store.set("owner@example.test", password); + for (const [email, secret] of [["owner@example.test", "a wrong test password"], ["unknown@example.test", password], ["not-an-email", "short"], ["owner@example.test", "x".repeat(1025)]]) { + vi.mocked(scrypt).mockClear(); vi.mocked(timingSafeEqual).mockClear(); + expect(await store.verify(email!, secret!)).toBeNull(); + expect(scrypt).toHaveBeenCalledExactlyOnceWith(expect.any(String), expect.any(Buffer), 64, expect.objectContaining({ N: 32768, r: 8, p: 1 }), expect.any(Function)); + expect(timingSafeEqual).toHaveBeenCalledTimes(1); + } +}); + +it("accepts spaces and long passwords up to 1 KB; refuses short or oversized input and malformed storage", async () => { + const { store, dir } = fixture(); + expect(passwordProblem("x".repeat(1024))).toBeNull(); + expect(passwordProblem("é".repeat(512))).toBeNull(); + expect(passwordProblem("é".repeat(513))).not.toBeNull(); + await expect(store.set("@example.test", password)).rejects.toThrow("individual"); + await expect(store.set("owner@example.test", "short")).rejects.toThrow("12"); + await store.set("owner@example.test", " " + password + " "); + expect(await store.verify("owner@example.test", password)).toBeNull(); + const file = join(dir, "passwords", readdirSync(join(dir, "passwords"))[0]!); + writeFileSync(file, "{}"); + await expect(store.verify("owner@example.test", password)).rejects.toThrow("storage"); +}); + +it("reset revokes all account sessions and stream tickets, including email-code sessions, but keeps independent pairings", async () => { + const { store, dir } = fixture(); + await store.set("owner@example.test", password); + const sessions = new SessionRegistry({ file: join(dir, "sessions.json"), emailScopes: () => ["admin", "client"], passwordVersion: email => store.version(email) }); + try { + const first = sessions.issue({ email: "owner@example.test", scopes: ["admin", "client"], label: "password browser" }); + const second = sessions.issue({ email: "owner@example.test", userId: "email-account", scopes: ["admin", "client"], label: "email browser" }); + const paired = sessions.issue({ scopes: ["admin", "client"], label: "independent device" }); + const ended: string[] = []; sessions.onSessionRevoked(id => ended.push(id)); + await store.set("owner@example.test", "the replacement password"); + expect(sessions.authenticate(first.token)).toBeNull(); + expect(sessions.authenticate(second.token)).toBeNull(); + expect(ended).toEqual(expect.arrayContaining([first.session.id, second.session.id])); + expect(sessions.authenticate(paired.token)).not.toBeNull(); + expect(await store.verify("owner@example.test", password)).toBeNull(); + expect(await store.verify("owner@example.test", "the replacement password")).not.toBeNull(); + } finally { sessions.close(); } +}); + +it("removing a credential invalidates its sessions even if membership is restored before their next check", async () => { + const { store, dir } = fixture(); + await store.set("owner@example.test", password); + const sessions = new SessionRegistry({ file: join(dir, "sessions.json"), emailScopes: () => ["admin", "client"], passwordVersion: email => store.version(email) }); + try { + const first = sessions.issue({ email: "owner@example.test", scopes: ["admin", "client"], label: "Fixture browser" }); + store.remove("owner@example.test"); + expect(sessions.authenticate(first.token)).toBeNull(); + expect(store.enabled()).toBe(false); + } finally { sessions.close(); } +}); diff --git a/server/passwords.ts b/server/passwords.ts new file mode 100644 index 0000000000..0f9c7ba766 --- /dev/null +++ b/server/passwords.ts @@ -0,0 +1,75 @@ +import { createHash, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto"; +import { mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { z } from "zod"; +import { normalizeAccountEmail } from "../electron/control-plane-client.mjs"; +import { writeFileAtomic } from "./atomic.ts"; + +const recordSchema = z.object({ + version: z.string().uuid(), + salt: z.string().regex(/^[a-f0-9]{32}$/), + hash: z.string().regex(/^[a-f0-9]{128}$/), +}).strict(); +const dummy = { version: "", salt: "00".repeat(16), hash: "00".repeat(64) }; +const parameters = { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }; + +export function passwordProblem(password: string): string | null { + if ([...password].length < 12) return "use at least 12 characters"; + if (Buffer.byteLength(password, "utf8") > 1024) return "use a password no longer than 1 KB"; + return null; +} + +function derive(password: string, salt: string): Promise { + return new Promise((resolve, reject) => scrypt(password, Buffer.from(salt, "hex"), 64, parameters, + (error, hash) => error ? reject(error) : resolve(hash))); +} + +/** Server-local credentials: only the CLI writes them, with owner-only permissions. */ +export class PasswordStore { + private readonly directory: string; + constructor(dataDir: string) { this.directory = join(dataDir, "passwords"); } + + private file(email: string): string { + return join(this.directory, `${createHash("sha256").update(normalizeAccountEmail(email)).digest("hex")}.json`); + } + + private read(email: string): z.infer | undefined { + try { return recordSchema.parse(JSON.parse(readFileSync(this.file(email), "utf8"))); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw new Error("Could not read local password storage."); + } + } + + enabled(): boolean { + try { return readdirSync(this.directory).some(name => /^[a-f0-9]{64}\.json$/.test(name)); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw new Error("Could not read local password storage."); + } + } + + remove(email: string): void { rmSync(this.file(email), { force: true }); } + + version(email: string): string | undefined { return this.read(email)?.version; } + + async set(email: string, password: string): Promise { + if (!normalizeAccountEmail(email)) throw new Error("give an individual email address for a password"); + const problem = passwordProblem(password); + if (problem) throw new Error(problem); + const salt = randomBytes(16).toString("hex"); + const hash = (await derive(password, salt)).toString("hex"); + mkdirSync(this.directory, { recursive: true, mode: 0o700 }); + writeFileAtomic(this.file(email), JSON.stringify({ version: randomUUID(), salt, hash }) + "\n", { mode: 0o600 }); + } + + async verify(email: string, password: string): Promise { + const record = this.read(email); + const held = record ?? dummy; + const valid = !passwordProblem(password); + // Unknown addresses and invalid passwords still pay the same scrypt and constant-time comparison cost. + const hash = await derive(valid ? password : "invalid password", held.salt); + const matches = timingSafeEqual(hash, Buffer.from(held.hash, "hex")); + return matches && valid && record && this.version(email) === record.version ? record.version : null; + } +} diff --git a/server/routes/dashboard.test.ts b/server/routes/dashboard.test.ts index 11ffc73a91..0c201af63d 100644 --- a/server/routes/dashboard.test.ts +++ b/server/routes/dashboard.test.ts @@ -51,7 +51,7 @@ async function listen(server: Server) { return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; } async function routes(overrides: Partial = {}, auth = ADMIN) { - const reporter = { status: vi.fn(() => ({ connected: false, url: null, workspaceId: null, lastReportAt: null, lastError: null, watching: false })), + const reporter = { status: vi.fn(() => ({ connected: false, accountLinked: false, url: null, workspaceId: null, lastReportAt: null, lastError: null, watching: false })), link: vi.fn(async (url: string) => ({ v: 1 as const, workspaceId: "workspace", claimUrl: `${url}/claim`, dashboardUrl: url, claimExpiresAt: 0 })), forget: vi.fn(async () => {}), start() {}, stop() {} }; const deps = { reporter, linkAgentBase: () => "https://link.test", env: {}, ...overrides }; const handlers = [createDashboardRoutes(deps)]; @@ -110,7 +110,7 @@ describe("dashboard link routes", () => { }); it("requires JSON mutations and exposes status and forget", async () => { const { call, reporter } = await routes(); - expect((await call()).status).toBe(200); + expect(await (await call()).json()).toMatchObject({ connected: false, accountLinked: false }); for (const method of ["POST", "DELETE"]) expect((await call(method, undefined, "text/plain")).status).toBe(415); expect(await (await call("DELETE")).json()).toEqual({ ok: true }); expect(reporter.forget).toHaveBeenCalledOnce(); }); diff --git a/server/sessions.ts b/server/sessions.ts index 8ae3d15cac..ac88564e29 100644 --- a/server/sessions.ts +++ b/server/sessions.ts @@ -52,6 +52,7 @@ const sessionSchema = z.object({ expiresAt: z.number(), userId: z.string().max(256).optional(), email: z.string().max(320).optional(), + passwordVersion: z.string().optional(), /** the team claim is signed by the Cloud admin and revalidated separately from local email membership. */ membershipAuthority: z.literal("team").optional(), /** A Team Cloud session's role in the team, from the Admin's claim. */ @@ -183,6 +184,8 @@ export interface SessionStoreOptions { now?: () => number; emailScopes?: EmailScopesResolver; emailScopesSnapshot?: () => EmailScopesResolver; + /** Current local credential generation; changing it revokes all account sessions for the email. */ + passwordVersion?: (email: string) => string | undefined; /** Between membershipChanged() calls, the hot paths (each request, stream frame and liveness check) recheck email * membership at most this often. Default 0: every call. */ recheckMs?: number; @@ -440,7 +443,7 @@ export class SessionRegistry { } } - issue(input: { label: string; scopes: Scope[]; userId?: string; email?: string }): { token: string; session: PublicSession } { + issue(input: { label: string; scopes: Scope[]; userId?: string; email?: string; passwordVersion?: string }): { token: string; session: PublicSession } { return this.issueAccount(input); } @@ -472,7 +475,7 @@ export class SessionRegistry { return ended.length; } - private issueAccount(input: { label: string; scopes: Scope[]; userId?: string; email?: string }): { token: string; session: PublicSession } { + private issueAccount(input: { label: string; scopes: Scope[]; userId?: string; email?: string; passwordVersion?: string }): { token: string; session: PublicSession } { this.refusePersonal(input.scopes); this.prune(); const now = this.now(); @@ -487,7 +490,7 @@ export class SessionRegistry { expiresAt: now + Math.min(SESSION_TTL_MS, SESSION_MAX_AGE_MS), }; if (input.userId) record.userId = input.userId; - if (input.email) record.email = input.email; + if (input.email) { record.email = input.email; record.passwordVersion = input.passwordVersion ?? this.options.passwordVersion?.(input.email); } this.sessions.push(record); this.lastSeenWrites.set(record.id, now); this.persist(); @@ -535,7 +538,8 @@ export class SessionRegistry { const revoked = eligible.filter((session) => { try { const allowed = resolveScopes?.(session.email!); - return !allowed || session.scopes.some((scope) => !allowed.includes(scope)); + return !allowed || session.scopes.some((scope) => !allowed.includes(scope)) || + (this.options.passwordVersion !== undefined && this.options.passwordVersion(session.email!) !== session.passwordVersion); } catch { return true; // missing or unreadable membership must fail closed } diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.ts index 1ecd5c6557..cfd321cf25 100644 --- a/server/workspace-backup-policy.ts +++ b/server/workspace-backup-policy.ts @@ -27,7 +27,7 @@ export function restoredWorkspaceConfig(portable: unknown, destination: unknown) } export function excludedWorkspaceAuthPath(path: string): boolean { - if (inSecretFolder(path)) return true; + if (inSecretFolder(path) || /^passwords(?:\/|$)/.test(path)) return true; if (/^command-allowlist\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true; if (/^mcp-oauth\.json(?:\.key)?(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true; // Pasted app tokens and native sign-ins, and their key, stay with the installation that connected them. diff --git a/src/components/BrowserSettingsRows.test.ts b/src/components/BrowserSettingsRows.test.ts index dea45109e3..b84c7c22ec 100644 --- a/src/components/BrowserSettingsRows.test.ts +++ b/src/components/BrowserSettingsRows.test.ts @@ -8,10 +8,12 @@ import { setLocale } from "@/lib/i18n"; import { ServerSitesRow } from "./BrowserSettingsRows"; const fixture = vi.hoisted(() => ({ + selfHosted: true, config: undefined as Record | undefined, api: vi.fn(), dispatch: vi.fn(), })); +vi.mock("@/lib/use-self-hosted", () => ({ useSelfHosted: () => fixture.selfHosted })); const owner = vi.hoisted(() => ({ value: true as boolean | null })); vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => owner.value })); vi.mock("@/state/store", () => ({ @@ -24,6 +26,7 @@ let root: Root; beforeEach(() => { vi.clearAllMocks(); + fixture.selfHosted = true; setLocale("en"); fixture.config = { browserEngine: { kind: "engine", engine: "agent-browser" } }; fixture.dispatch.mockImplementation((action: { type: string; config?: Record }) => { @@ -58,6 +61,13 @@ describe("Open sites on this server", () => { expect(sites()?.getAttribute("aria-checked")).toBe("false"); }); + it.each([true, false])("uses server-specific copy only for self-hosting (%s)", (selfHosted) => { + fixture.selfHosted = selfHosted; + fixture.config = { features: { browser: true }, browserEngine: { kind: "engine", serverSites: false } }; + show(); + expect(host.textContent).toContain(selfHosted ? "Includes this server’s local network" : "Includes your local network"); + }); + it("turns it on as browserEngine.egress.localNetwork and shows the server's answer", async () => { fixture.config = { features: { browser: true }, browserEngine: { kind: "engine", serverSites: false } }; const saved = { features: { browser: true }, browserEngine: { kind: "engine", serverSites: true } }; diff --git a/src/components/BrowserSettingsRows.tsx b/src/components/BrowserSettingsRows.tsx index 46feed194a..c17ad6b726 100644 --- a/src/components/BrowserSettingsRows.tsx +++ b/src/components/BrowserSettingsRows.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { browserAvailable, browserUnavailableReason, builtInBrowserEnabled } from "@/lib/feature-flags"; import { t } from "@/lib/i18n"; +import { useSelfHosted } from "@/lib/use-self-hosted"; import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin"; import { api, useStore, type ConfigStatus } from "@/state/store"; import { SettingRow, Switch } from "./SettingsPrimitives"; @@ -67,6 +68,7 @@ export function BuiltInBrowserRow() { export function ServerSitesRow() { const { state } = useStore(); const owner = useOwnerOrAdmin(); + const selfHosted = useSelfHosted(); const on = state.config?.browserEngine?.serverSites; const { saving, error, save } = useConfigSave(); if (on === undefined || owner !== true || !builtInBrowserEnabled(state.config)) return null; @@ -74,7 +76,7 @@ export function ServerSitesRow() { return ( {error}

: null} > ({ values: [] as unknown[], index: 0, effects: [] as EffectCallback[], refs: [] as { current: unknown }[], ref: 0, state: {} as any, dispatch: null as any })); +const f = vi.hoisted(() => ({ selfHosted: false as boolean | null, values: [] as unknown[], index: 0, effects: [] as EffectCallback[], refs: [] as { current: unknown }[], ref: 0, state: {} as any, dispatch: null as any })); +vi.mock("@/lib/use-self-hosted", () => ({ useSelfHosted: () => f.selfHosted })); vi.mock("react", async original => ({ ...await original(), useState: (initial: unknown) => { const index = f.index++; if (!(index in f.values)) f.values[index] = typeof initial === "function" ? initial() : initial; return [f.values[index], (next: unknown) => { f.values[index] = typeof next === "function" ? (next as (value: unknown) => unknown)(f.values[index]) : next; }]; }, @@ -36,6 +37,7 @@ const today = (messages = 1, over: { shown?: number; lastShownAt?: number } = {} storage.set(NUDGE_KEY, JSON.stringify({ day: dayKey(Date.now()), sessions: 1, messages, shown: 0, lastShownAt: 0, ...over })); beforeEach(() => { + f.selfHosted = false; vi.clearAllMocks(); setLocale("en"); storage = new Map(); f.dispatch = vi.fn(); today(); vi.stubGlobal("localStorage", { getItem: (key: string) => storage.get(key) ?? null, setItem: (key: string, value: string) => storage.set(key, value) }); vi.stubGlobal("sessionStorage", { getItem: () => null, setItem: () => {} }); @@ -139,3 +141,7 @@ describe("the dusk cloud offer in the sidebar's spot", () => { expect(await launch()).not.toContain("cloud-invested"); }); }); + +it("does not offer managed hosting on an operator-managed server or while detection is pending", async () => { + for (const value of [true, null]) { f.selfHosted = value; expect(await launch()).not.toContain('data-spot-card'); } +}); diff --git a/src/components/CloudUpsell.tsx b/src/components/CloudUpsell.tsx index dc6d9a3b28..b904108c48 100644 --- a/src/components/CloudUpsell.tsx +++ b/src/components/CloudUpsell.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { useSelfHosted } from "@/lib/use-self-hosted"; import { storeApp } from "@/lib/store-app"; import type { CloudSource } from "@/lib/cloud-plan"; import { investedBy, type InvestedFacts } from "../../shared/cloud-upsell"; @@ -18,6 +19,7 @@ import { deviceWord } from "./vps-link/parts"; export function useCloudUpsell(): { allowed: boolean | null; open: (source: CloudSource) => void } { const { state, dispatch } = useStore(); const plan = useCloudPlan(); + const selfHosted = useSelfHosted(); const organization = window.duskDesktop?.organization; const [managed, setManaged] = useState(organization ? null : false); useEffect(() => { @@ -30,7 +32,7 @@ export function useCloudUpsell(): { allowed: boolean | null; open: (source: Clou void organization.state().then(next => { if (!updated) accept(next); }).catch(() => {}); return () => { active = false; unsubscribe(); }; }, [organization]); - const here = !storeApp() && localDesktopPage() && window.duskDesktop?.remoteClient?.active !== true && Boolean(state.config) + const here = selfHosted === false && !storeApp() && localDesktopPage() && window.duskDesktop?.remoteClient?.active !== true && Boolean(state.config) && !state.config?.cloudHome && !state.config?.managedPolicy; const allowed = cloudUpsellAllowed({ here, view: plan?.view ?? null, managed }); const signedOut = plan?.view.kind === "signed-out"; diff --git a/src/components/DataSharingRows.test.ts b/src/components/DataSharingRows.test.ts new file mode 100644 index 0000000000..d27f09c671 --- /dev/null +++ b/src/components/DataSharingRows.test.ts @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom +import { act, createElement } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { setLocale } from "@/lib/i18n"; + +const fixture = vi.hoisted(() => ({ selfHosted: true as boolean | null, api: vi.fn() })); +vi.mock("@/state/api", () => ({ api: fixture.api })); +vi.mock("@/lib/use-self-hosted", () => ({ useSelfHosted: () => fixture.selfHosted })); +vi.mock("@/lib/product-analytics", () => ({ setUsageAnalytics: vi.fn(), usageSharingChanged: vi.fn() })); +const { DataSharingRows } = await import("./DataSharingRows"); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +let host: HTMLDivElement; +let root: Root; +let enabled: boolean; +let link: () => Promise<{ connected: boolean; accountLinked?: boolean }>; + +beforeEach(() => { + setLocale("en"); + fixture.selfHosted = true; + enabled = true; + link = async () => ({ connected: false }); + fixture.api.mockReset(); + fixture.api.mockImplementation(async (path: string, init?: RequestInit) => { + if (path === "/api/dashboard/link") return link(); + if (path === "/api/dashboard/usage-signals") { + if (init?.body) enabled = JSON.parse(String(init.body)).enabled; + return { enabled, notes: null, askUsage: false, askNotes: false }; + } + throw new Error(`Unexpected path: ${path}`); + }); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(() => { act(() => root.unmount()); host.remove(); }); +const render = () => act(async () => root.render(createElement(DataSharingRows))); +const toggle = () => host.querySelector("[data-help-improve]"); + +describe("self-hosted help improve visibility", () => { + it("hides the unlinked option without changing the saved choice or the other privacy rows", async () => { + await render(); + expect(toggle()).toBeNull(); + expect(host.textContent).not.toContain("Help improve dusk bot"); + expect(host.querySelector("[data-session-notes]")).not.toBeNull(); + expect(host.querySelector('[data-panel-page="shared-data"]')).not.toBeNull(); + expect(enabled).toBe(true); + expect(fixture.api.mock.calls.every(([, init]) => !init?.method || init.method === "GET")).toBe(true); + }); + + it("waits for a confirmed link, then preserves the working switch", async () => { + let finish!: (value: { connected: boolean; accountLinked?: boolean }) => void; + link = () => new Promise(resolve => { finish = resolve; }); + await render(); + expect(toggle()).toBeNull(); + await act(async () => finish({ connected: true, accountLinked: true })); + expect(toggle()?.getAttribute("aria-checked")).toBe("true"); + await act(async () => toggle()!.click()); + expect(enabled).toBe(false); + expect(toggle()?.getAttribute("aria-checked")).toBe("false"); + expect(fixture.api).toHaveBeenCalledWith("/api/dashboard/usage-signals", { method: "PUT", body: '{"enabled":false}' }); + }); + + it.each([false, undefined])("hides connected enrollment without a confirmed account (%s)", async (accountLinked) => { + link = async () => ({ connected: true, accountLinked }); + await render(); + expect(toggle()).toBeNull(); + expect(enabled).toBe(true); + expect(fixture.api.mock.calls.every(([, init]) => !init?.method || init.method === "GET")).toBe(true); + }); + + it("keeps the option hidden when link status cannot be read", async () => { + link = async () => { throw new Error("Unavailable"); }; + await render(); + expect(toggle()).toBeNull(); + }); + + it("keeps desktop and cloud behavior without requiring the workspace link", async () => { + fixture.selfHosted = false; + await render(); + expect(toggle()).not.toBeNull(); + expect(fixture.api).not.toHaveBeenCalledWith("/api/dashboard/link"); + }); + + it("does not flash the option while the deployment type is unknown", async () => { + fixture.selfHosted = null; + await render(); + expect(toggle()).toBeNull(); + expect(fixture.api).not.toHaveBeenCalledWith("/api/dashboard/link"); + }); +}); diff --git a/src/components/DataSharingRows.tsx b/src/components/DataSharingRows.tsx index f4438c8595..990d1c3712 100644 --- a/src/components/DataSharingRows.tsx +++ b/src/components/DataSharingRows.tsx @@ -1,4 +1,7 @@ +import { useEffect, useState } from "react"; import { t } from "@/lib/i18n"; +import { api } from "@/state/api"; +import { useSelfHosted } from "@/lib/use-self-hosted"; import { PRIVACY_SUMMARY_URL, openExternalLink } from "@/lib/app-links"; import { useHelpImprove } from "@/lib/help-improve"; import { useSubPage } from "./ListRows"; @@ -10,12 +13,23 @@ export const SHARED_DATA_PAGE = "shared-data"; export function DataSharingRows() { const { signals, failed, set } = useHelpImprove("settings"); const sub = useSubPage(); + const selfHosted = useSelfHosted(); + const [accountLinked, setAccountLinked] = useState(false); + useEffect(() => { + if (selfHosted !== true) return; + let current = true; + void api<{ accountLinked?: boolean }>("/api/dashboard/link") + .then(answer => { if (current) setAccountLinked(answer.accountLinked === true); }) + .catch(() => { if (current) setAccountLinked(false); }); + return () => { current = false; }; + }, [selfHosted]); + const showHelpImprove = selfHosted === false || (selfHosted === true && accountLinked); if (signals === null) return failed ?

{t("settings.dataSharing.unavailable")}

: null; const counts = signals.enabled && !signals.askUsage; const notes = counts && signals.notes === true; return ( <> - + {showHelpImprove && {t("settings.dataSharing.improveHint")}{" "} - {sent ? ( + {mode === "email" && sent ? ( ) : null} + {mode === "password" && emailOffered ? : null} + {mode === "email" && passwordOffered ? : null} @@ -226,6 +243,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial + {passwordOffered ? : null} {emailOffered ? (