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")}{" "}
void openExternalLink(PRIVACY_SUMMARY_URL)}
className="relative rounded-sm text-current no-underline underline-offset-2 before:absolute before:-inset-y-1 before:inset-x-0 hover:underline focus-visible:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
@@ -25,7 +39,7 @@ export function DataSharingRows() {
>}
message={failed ? {t("settings.dataSharing.error")}
: null}>
void set({ enabled: !counts })} />
-
+ }
{t("settings.dataSharing.notesHint")}
{" "}{t(counts ? "settings.dataSharing.notesDeletes" : "settings.dataSharing.notesNeedsImprove")}
diff --git a/src/components/LocalComputerSection.dom.test.ts b/src/components/LocalComputerSection.dom.test.ts
index bc605ecea9..dc5d45a5fb 100644
--- a/src/components/LocalComputerSection.dom.test.ts
+++ b/src/components/LocalComputerSection.dom.test.ts
@@ -4,6 +4,7 @@ import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
const local = vi.hoisted(() => ({ openPlaceSetup: vi.fn() }));
+vi.mock("@/lib/use-self-hosted", () => ({ useSelfHosted: () => true }));
vi.mock("@/lib/place-setup", () => ({ openPlaceSetup: local.openPlaceSetup }));
vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({ ready: true, capabilities: { host: { platform: "darwin" }, localComputer: { available: true } } }) }));
@@ -20,9 +21,9 @@ afterEach(() => {
vi.useRealTimers();
});
-it("loads only local and VPS inventories and offers the existing VPS setup flow", async () => {
+it.each([true, false])("loads inventories and offers server setup only with desktop support (%s)", async (desktop) => {
vi.useFakeTimers();
- window.duskDesktop = { localControl: { retry: vi.fn() } } as any;
+ if (desktop) window.duskDesktop = { localControl: { retry: vi.fn() }, workspaces: { add: vi.fn() } } as any;
const paths: string[] = [];
vi.stubGlobal("fetch", vi.fn(async (path: string) => {
paths.push(path);
@@ -40,8 +41,10 @@ it("loads only local and VPS inventories and offers the existing VPS setup flow"
try {
await act(async () => { root.render(createElement(LocalComputerSection)); });
// the server's own description (server-compat), read once for the egress row, and the two inventories
- expect(paths.sort()).toEqual(["/.well-known/duskbot/environment", "/.well-known/openmausbot/environment", "/api/computer/egress", "/api/computers/vps", "/api/local-computer", "/api/mac"]);
- expect(container.textContent).toContain("Add your own server");
+ expect(paths.filter(path => path.startsWith("/api/")).sort()).toEqual(["/api/computer/egress", "/api/computers/vps", "/api/local-computer", "/api/mac"]);
+ expect(container.textContent?.includes("Add your own server")).toBe(desktop);
+ expect(container.textContent).toContain("This server");
+ expect(container.textContent).toContain("Private desktop");
expect(local.openPlaceSetup).not.toHaveBeenCalled();
expect(container.textContent).not.toMatch(/\x42oat|credit|cloud desktop/i);
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
diff --git a/src/components/LocalComputerSection.tsx b/src/components/LocalComputerSection.tsx
index ec5bca66bc..f05cee7043 100644
--- a/src/components/LocalComputerSection.tsx
+++ b/src/components/LocalComputerSection.tsx
@@ -13,6 +13,8 @@ import { SettingsSelect } from "./SettingsSelect";
import { useCopyFeedback } from "@/lib/copy-text";
import { cn } from "@/lib/cn";
import { useStore } from "@/state/store";
+import { useSelfHosted } from "@/lib/use-self-hosted";
+import { thisComputerPage, vpsLinkAvailable } from "@/lib/vps-link";
import { openPlaceSetup } from "@/lib/place-setup";
import { VpsComputersCard } from "./VpsComputersCard";
import { DirectLinkRow } from "./DirectLinkRow";
@@ -454,6 +456,8 @@ export function LocalVmIdleTimeoutSetting({
}
export function LocalComputerSection() {
+ const selfHosted = useSelfHosted();
+ const canAddServer = thisComputerPage() && (vpsLinkAvailable() || Boolean(window.duskDesktop?.workspaces?.add));
const cloudHome = useStore().state.config?.cloudHome === true;
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
@@ -870,8 +874,8 @@ export function LocalComputerSection() {
return (
<>
{announcer}
-
- {vpsConfigured === false && !vpsLoading && !vpsUnavailableReason && (typeof window === "undefined" || window.duskDesktop?.remoteClient?.active !== true) && openPlaceSetup("server")} />}
+ {(canAddServer || vpsConfigured !== false || vpsLoading || vpsUnavailableReason) &&
+ {vpsConfigured === false && !vpsLoading && !vpsUnavailableReason && canAddServer && openPlaceSetup("server")} />}
void removeVpsComputer(instance)}
onRestart={(instance) => void restartVpsComputer(instance)}
/>
-
+ }
{cloudHome && (
@@ -894,7 +898,7 @@ export function LocalComputerSection() {
)}
{!cloudHome && (
-
+
diff --git a/src/components/MobilePairingCard.tsx b/src/components/MobilePairingCard.tsx
index 8dbfb290ac..d6ee36e43e 100644
--- a/src/components/MobilePairingCard.tsx
+++ b/src/components/MobilePairingCard.tsx
@@ -1,3 +1,4 @@
+import { useSelfHosted } from "@/lib/use-self-hosted";
import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import { Apple, ChevronLeft } from "../icons";
import { PairingQr } from "./PairingQr";
@@ -120,6 +121,7 @@ export function MobilePairingCard({ remote, cloudHome = false, email, direct, ch
/** the code at once, for either phone, with no linked phones or phone picker around it; Done after a link calls onDone */
direct?: { onDone(): void };
}) {
+ const selfHosted = useSelfHosted();
const [devices, setDevices] = useState(null);
const [cloudSignIns, setCloudSignIns] = useState(null);
const signInsSeen = useRef(cloudSignIns);
@@ -532,7 +534,7 @@ export function MobilePairingCard({ remote, cloudHome = false, email, direct, ch
const platformStep = (live: boolean) => (
- {heading(live, t("settings.phone.whichTitle"), t(cloudHome ? "settings.phone.whichSubCloud" : "settings.phone.whichSub"))}
+ {heading(live, t("settings.phone.whichTitle"), t(cloudHome ? "settings.phone.whichSubCloud" : selfHosted ? "selfHosted.phone.hint" : "settings.phone.whichSub"))}
{signInAsk &&
{t("settings.phone.logInToConnect")}
}
{phoneCard("ios")}{phoneCard("android")}
diff --git a/src/components/ProIntroduction.test.ts b/src/components/ProIntroduction.test.ts
index 2ebda12851..efe0f41b87 100644
--- a/src/components/ProIntroduction.test.ts
+++ b/src/components/ProIntroduction.test.ts
@@ -5,7 +5,8 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { CloudAccountState } from "../../electron/cloud-account.mjs";
import type { CloudOffer } from "../../electron/cloud-home.mjs";
-const f = vi.hoisted(() => ({ values: [] as unknown[], index: 0, effects: [] as EffectCallback[], dispatch: null as any }));
+const f = vi.hoisted(() => ({ selfHosted: false as boolean | null, values: [] as unknown[], index: 0, effects: [] as EffectCallback[], 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] = next; }]; },
@@ -26,6 +27,7 @@ let offer: CloudOffer | null;
let openExternal: ReturnType;
let bridge: Record>;
beforeEach(() => {
+ f.selfHosted = false;
vi.clearAllMocks(); f.values = []; f.index = 0; f.effects = []; f.dispatch = vi.fn(); offer = TRIAL;
openExternal = vi.fn().mockResolvedValue(true);
bridge = { state: vi.fn(async () => signedOut), onState: vi.fn(() => () => {}), offer: vi.fn(async () => offer) };
@@ -109,3 +111,7 @@ it("never offers a plan to anyone who pays, may pay, or whose state is unknown;
vi.stubGlobal("window", {});
expect(await card(signedOut)).toBe("");
});
+
+it("does not show plan offers on a self-hosted server or while detection is pending", async () => {
+ for (const value of [true, null]) { f.selfHosted = value; expect(await card(signedOut)).toBe(""); expect(bridge.offer).not.toHaveBeenCalled(); }
+});
diff --git a/src/components/ProIntroduction.tsx b/src/components/ProIntroduction.tsx
index badf5ab848..7264fe7d78 100644
--- a/src/components/ProIntroduction.tsx
+++ b/src/components/ProIntroduction.tsx
@@ -1,3 +1,4 @@
+import { useSelfHosted } from "@/lib/use-self-hosted";
import { useEffect, useState } from "react";
import { Cloud, Crown } from "../icons";
import type { CloudAccountState } from "../../electron/cloud-account.mjs";
@@ -29,9 +30,10 @@ export function useCloudPlan(): { view: CloudPlanView; account: CloudAccountStat
export function ProSettingsCard() {
const { dispatch } = useStore();
const plan = useCloudPlan();
- const offering = plan !== null && buyOfferAllowed(plan.view);
+ const selfHosted = useSelfHosted();
+ const offering = selfHosted === false && plan !== null && buyOfferAllowed(plan.view);
const offer = useCloudOffer(offering, plan?.account?.offer);
- if (!plan) return null;
+ if (!plan || selfHosted !== false) return null;
const { view } = plan;
if (offering) {
const trial = offerTrialDays(offer) !== null, moneyBack = moneyBackLine(offer);
@@ -71,9 +73,10 @@ export function ProSettingsCard() {
export function CloudPlanRow({ place, usage = null, upgrade }: { place: "account" | "plan"; usage?: CloudUsage | null; upgrade?: UpgradeUi }) {
const { dispatch } = useStore();
const plan = useCloudPlan();
- const offering = plan !== null && buyOfferAllowed(plan.view);
+ const selfHosted = useSelfHosted();
+ const offering = selfHosted === false && plan !== null && buyOfferAllowed(plan.view);
const offer = useCloudOffer(offering, plan?.account?.offer);
- if (!plan) return null;
+ if (!plan || selfHosted !== false) return null;
if (offering) {
const trial = offerTrialDays(offer) !== null;
const cheapest = offer && offer.plans.length ? Math.min(...offer.plans.map((entry) => entry.amount)) : null;
@@ -104,7 +107,8 @@ export function CloudPlanRow({ place, usage = null, upgrade }: { place: "account
export function CloudPlanFootnote() {
const plan = useCloudPlan();
- const offering = plan !== null && buyOfferAllowed(plan.view);
+ const selfHosted = useSelfHosted();
+ const offering = selfHosted === false && plan !== null && buyOfferAllowed(plan.view);
const offer = useCloudOffer(offering, plan?.account?.offer);
if (!offering) return null;
return [t("pro.disclaimer"), moneyBackLine(offer)].filter(Boolean).join(" ");
diff --git a/src/components/ProfileSettings.test.ts b/src/components/ProfileSettings.test.ts
index 6d5879985c..dfd202e79b 100644
--- a/src/components/ProfileSettings.test.ts
+++ b/src/components/ProfileSettings.test.ts
@@ -5,12 +5,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ConfigStatus } from "@/state/store";
-const fixture = vi.hoisted(() => ({ config: {} as Partial, dispatch: vi.fn(), api: vi.fn() }));
+const fixture = vi.hoisted(() => ({ selfHosted: false as boolean | null, config: {} as Partial, dispatch: vi.fn(), api: vi.fn() }));
vi.mock("@/state/store", async (importOriginal) => ({
...(await importOriginal()),
api: fixture.api,
useStore: () => ({ state: { config: fixture.config }, dispatch: fixture.dispatch }),
}));
+vi.mock("@/lib/use-self-hosted", () => ({ useSelfHosted: () => fixture.selfHosted }));
vi.mock("./AboutMeSettings", () => ({ AboutMeSettings: () => null }));
const { ProfileFields, profilePhotoFileProblem, profilePhotoSizeProblem } = await import("./ProfileSettings");
@@ -22,6 +23,7 @@ let root: Root;
const photo = "/api/attachments/5f0c2b1e-8a43-4c1d-9e7a-2b6f1d3c4e5a.webp";
beforeEach(() => {
+ fixture.selfHosted = false;
fixture.dispatch.mockReset();
fixture.api.mockReset();
host = document.createElement("div");
@@ -145,6 +147,17 @@ describe("name and email", () => {
expect(put).toHaveBeenLastCalledWith({ profile: { name: "Ada", email: "ada@example.com" } });
});
+ it.each([true, null])("hides the email on a self-hosted or unresolved server and leaves it untouched when saving a name (%s)", async (selfHosted) => {
+ fixture.selfHosted = selfHosted;
+ fixture.config = { profile: { name: "Ada", email: "saved@example.test" } };
+ await act(async () => root.render(createElement(ProfileFields)));
+ expect(input("Email")).toBeNull();
+ type(input("Your name"), "Ada Updated");
+ await blur(input("Your name"));
+ expect(put).toHaveBeenCalledWith({ profile: { name: "Ada Updated" } });
+ expect(host.querySelector('[role="alert"]')).toBeNull();
+ });
+
it("caps the name at a bot name's length", async () => {
await act(async () => root.render(createElement(ProfileFields)));
expect(input("Your name").maxLength).toBe(80);
diff --git a/src/components/ProfileSettings.tsx b/src/components/ProfileSettings.tsx
index f5981d269d..8be7afa343 100644
--- a/src/components/ProfileSettings.tsx
+++ b/src/components/ProfileSettings.tsx
@@ -1,3 +1,4 @@
+import { useSelfHosted } from "@/lib/use-self-hosted";
import { cn } from "@/lib/cn";
import { textFieldCls } from "./ui/GrokDialog";
import { useEffect, useId, useRef, useState } from "react";
@@ -158,6 +159,7 @@ function ProfilePhoto({ face }: { face?: PersonFace | null }) {
/** `face` is the signed-in account's (its photo or chosen avatar), shown while this place has no photo of its own. */
export function ProfileFields({ face }: { face?: PersonFace | null }) {
+ const showEmail = useSelfHosted() === false;
const { state, dispatch } = useStore();
const [name, setName] = useState(state.config?.profile?.name ?? "");
const [email, setEmail] = useState(state.config?.profile?.email ?? "");
@@ -177,8 +179,8 @@ export function ProfileFields({ face }: { face?: PersonFace | null }) {
.catch(() => {});
return;
}
- const emailOk = isProfileEmail(email);
- setEmailInvalid(!emailOk);
+ const emailOk = showEmail && isProfileEmail(email);
+ setEmailInvalid(showEmail && !emailOk);
void fetch("/api/config", {
method: "PUT",
headers: { "content-type": "application/json" },
@@ -201,7 +203,7 @@ export function ProfileFields({ face }: { face?: PersonFace | null }) {
{t("settings.profile.name")}
setName(e.target.value)} onBlur={save} placeholder={t("settings.profile.name")} className={inputClass} />
-
+ {showEmail &&
{t("phone.signIn.email")}
{emailInvalid &&
{t("settings.profile.emailInvalid")}
}
-
+
}
);
diff --git a/src/components/ServerPairingCard.elsewhere.test.ts b/src/components/ServerPairingCard.elsewhere.test.ts
index 0681d8d274..736765f043 100644
--- a/src/components/ServerPairingCard.elsewhere.test.ts
+++ b/src/components/ServerPairingCard.elsewhere.test.ts
@@ -3,13 +3,14 @@ import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, expect, it, vi } from "vitest";
// React's state is replayed by hand: the offer is the fourth useState
-const f = vi.hoisted(() => ({ values: [] as unknown[], index: 0 }));
+const f = vi.hoisted(() => ({ values: [] as unknown[], index: 0, selfHosted: false }));
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 as () => unknown)() : initial; return [f.values[index], () => {}]; },
useRef: (initial: unknown) => { const index = f.index++; if (!(index in f.values)) f.values[index] = { current: initial }; return f.values[index]; },
useEffect: () => {},
}));
+vi.mock("@/lib/use-self-hosted", () => ({ useSelfHosted: () => f.selfHosted }));
import { t } from "@/lib/i18n";
import { ServerPairingCard, type PairingOffer } from "./ServerPairingCard";
@@ -21,7 +22,7 @@ function withOffer(offer: PairingOffer): string {
return renderToStaticMarkup(createElement(() => ServerPairingCard({ initialSession: admin, elsewhere: { connect: null } })));
}
-beforeEach(() => { f.values = []; f.index = 0; });
+beforeEach(() => { f.values = []; f.index = 0; f.selfHosted = false; });
it("says when a server's code has no public address behind it, and where a phone links instead", () => {
const html = withOffer({ id: "p", code: "ABCD-EFGH-JKLM", expiresAt: Date.now() + 60_000, url: null, hint: "no public address" });
@@ -37,3 +38,10 @@ it("says nothing more when the code comes with a link", () => {
expect(html).toContain(t("settings.elsewhere.codeLive", { minutes: 1 }).split(".")[0]);
expect(html).not.toContain("data-pairing-no-address");
});
+
+it.each([true, false])("names the pairing code for the hosting environment (%s)", (selfHosted) => {
+ f.selfHosted = selfHosted;
+ const html = withOffer({ id: "p", code: "ABCD-EFGH-JKLM", expiresAt: Date.now() + 60_000, url: null, hint: null });
+ expect(html).toContain(selfHosted ? "This server's code" : "This computer's code");
+ expect(html).toContain("Access");
+});
diff --git a/src/components/ServerPairingCard.tsx b/src/components/ServerPairingCard.tsx
index 1679c8af80..b8be12690a 100644
--- a/src/components/ServerPairingCard.tsx
+++ b/src/components/ServerPairingCard.tsx
@@ -4,6 +4,7 @@ import { requireUserPresence } from "@/lib/user-presence";
import { KeyRound } from "../icons";
import { t } from "@/lib/i18n";
+import { useSelfHosted } from "@/lib/use-self-hosted";
import { copyText, type CopyFeedback } from "@/lib/copy-text";
import { api, ApiError } from "@/state/store";
import { isOwnerOrAdmin, readSessionState, type SessionState } from "../lib/session";
@@ -57,6 +58,7 @@ export function ServerPairingCard({ initialSession = null, cloudHome = false, fo
/** Settings > Computer > Connect from elsewhere: this computer's code, the row that connects to another computer, and
* who a code lets in */
elsewhere?: { connect: ReactNode } }) {
+ const selfHosted = useSelfHosted();
const [session, setSession] = useState(initialSession);
const [computerName, setComputerName] = useState(null);
const [scope, setScope] = useState<"admin" | "client">("admin");
@@ -257,7 +259,7 @@ export function ServerPairingCard({ initialSession = null, cloudHome = false, fo
return (
{t("settings.elsewhere.intro")}
-
+
{live &&
{live.code}}
diff --git a/src/components/ServerSignOut.dom.test.ts b/src/components/ServerSignOut.dom.test.ts
new file mode 100644
index 0000000000..18ea43281b
--- /dev/null
+++ b/src/components/ServerSignOut.dom.test.ts
@@ -0,0 +1,53 @@
+// @vitest-environment happy-dom
+import { act, createElement, Fragment } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+import type { SessionState } from "@/lib/session";
+import { useServerSignOut } from "./ServerSignOut";
+
+const logout = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/session", () => ({ signOutServerSession: logout }));
+vi.mock("./ConfirmDialog", () => ({ ConfirmDialog: (p: { open: boolean; body: import("react").ReactNode; pending: boolean; onConfirm(): void; onCancel(): void }) => p.open ? createElement("div", { role: "dialog" }, p.body, createElement("button", { disabled: p.pending, onClick: p.onConfirm }, "Confirm"), createElement("button", { disabled: p.pending, onClick: p.onCancel }, "Cancel")) : null }));
+const session: SessionState = { kind: "session", id: "fixture", label: "browser", scopes: ["client"], expiresAt: 1 };
+let root: Root | undefined;
+function Fixture({ state }: { state: SessionState | null }) {
+ const signOut = useServerSignOut(state);
+ return createElement(Fragment, null, signOut.request && createElement("button", { onClick: signOut.request }, "Sign out"), signOut.dialog);
+}
+async function mount(state: SessionState | null) {
+ document.body.innerHTML = '
';
+ root = createRoot(document.getElementById("root")!);
+ await act(async () => root!.render(createElement(Fixture, { state })));
+}
+async function click(text: string) {
+ await act(async () => [...document.querySelectorAll("button")].find(b => b.textContent === text)!.click());
+}
+afterEach(async () => { await act(async () => root?.unmount()); root = undefined; vi.restoreAllMocks(); vi.clearAllMocks(); delete window.duskDesktop; });
+
+it("offers browser logout to chat-only sessions, but leaves cancellation signed in", async () => {
+ await mount(session); await click("Sign out"); await click("Cancel");
+ expect(logout).not.toHaveBeenCalled(); expect(document.querySelector('[role="dialog"]')).toBeNull();
+});
+it.each([null, { kind: "loopback" } as SessionState, { kind: "unreachable", error: "offline" } as SessionState])("does not offer session logout without a browser session: %j", async state => {
+ await mount(state); expect(document.querySelector("button")).toBeNull();
+});
+it("keeps the desktop account flow separate", async () => {
+ window.duskDesktop = {} as NonNullable
;
+ await mount(session); expect(document.querySelector("button")).toBeNull();
+});
+it("shows a failed request and permits retry without navigating away", async () => {
+ const navigate = vi.spyOn(window.location, "replace").mockImplementation(() => {});
+ logout.mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(undefined);
+ await mount(session); await click("Sign out"); await click("Confirm");
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain("Could not sign out");
+ expect(navigate).not.toHaveBeenCalled(); await click("Confirm");
+ expect(navigate).toHaveBeenCalledWith("/pair"); expect(logout).toHaveBeenCalledTimes(2);
+});
+it("waits for revocation before leaving and prevents duplicate requests", async () => {
+ const navigate = vi.spyOn(window.location, "replace").mockImplementation(() => {});
+ let finish!: () => void;
+ logout.mockReturnValue(new Promise(resolve => { finish = resolve; }));
+ await mount(session); await click("Sign out"); await click("Confirm"); await click("Confirm");
+ expect(logout).toHaveBeenCalledOnce(); expect(navigate).not.toHaveBeenCalled();
+ await act(async () => finish()); expect(navigate).toHaveBeenCalledWith("/pair");
+});
diff --git a/src/components/ServerSignOut.tsx b/src/components/ServerSignOut.tsx
new file mode 100644
index 0000000000..b334ac5062
--- /dev/null
+++ b/src/components/ServerSignOut.tsx
@@ -0,0 +1,33 @@
+import { useRef, useState } from "react";
+import { t } from "@/lib/i18n";
+import { signOutServerSession, type SessionState } from "@/lib/session";
+import { ConfirmDialog } from "./ConfirmDialog";
+
+export function useServerSignOut(session: SessionState | null) {
+ const [open, setOpen] = useState(false);
+ const [pending, setPending] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const busy = useRef(false);
+ const available = session?.kind === "session" && !window.duskDesktop;
+ async function confirm() {
+ if (!available || busy.current) return;
+ busy.current = true;
+ setPending(true);
+ setFailed(false);
+ try {
+ await signOutServerSession();
+ window.location.replace("/pair");
+ } catch {
+ setFailed(true);
+ } finally {
+ busy.current = false;
+ setPending(false);
+ }
+ }
+ return {
+ request: available ? () => { setFailed(false); setOpen(true); } : undefined,
+ dialog: {t("serverSignOut.body")}{failed && {t("serverSignOut.failed")}
}>}
+ tone="neutral" pending={pending} onCancel={() => setOpen(false)} onConfirm={() => void confirm()} />,
+ };
+}
diff --git a/src/components/SettingsModal.grok.test.ts b/src/components/SettingsModal.grok.test.ts
index c30f4f91b0..0a1b009826 100644
--- a/src/components/SettingsModal.grok.test.ts
+++ b/src/components/SettingsModal.grok.test.ts
@@ -288,3 +288,9 @@ describe("where every section lives now", () => {
expect(openSettings()).toEqual({ type: "toggleAppSettings", open: true, section: "general" });
});
});
+
+it("offers diagnostics only when this client can export them", () => {
+ expect(open("updates")).not.toContain('data-settings-open="diagnostics"');
+ Object.assign(window.duskDesktop!, { exportDiagnostics: vi.fn() });
+ expect(open("updates")).toContain('data-settings-open="diagnostics"');
+});
diff --git a/src/components/SettingsPanes.tsx b/src/components/SettingsPanes.tsx
index 49bc19818c..d681c44465 100644
--- a/src/components/SettingsPanes.tsx
+++ b/src/components/SettingsPanes.tsx
@@ -1,3 +1,4 @@
+import { useSelfHosted } from "@/lib/use-self-hosted";
import { useId, useRef, useState, type ReactNode } from "react";
import { useSettledReveal } from "./settled-reveal";
import { cn } from "@/lib/cn";
@@ -107,6 +108,7 @@ function PageRow({ page, title, value, hint, ...rest }: { page: string; title: s
/** Grok's account card: the person's initials or photo, their name and the account they are signed in with, then Add
* account and Sign Out as pills (or Add, for a name, where nobody signs in); the name opens a small form. */
export function AccountRows() {
+ const selfHosted = useSelfHosted();
const { state } = useStore();
const accounts = useAccounts();
const [editing, setEditing] = useState(false);
@@ -150,7 +152,7 @@ export function AccountRows() {
)}
{/* signed out: sign in continues in the browser for its context (the account context redirect), never an in-app form */}
- {!active && window.duskDesktop?.accounts && window.duskDesktop?.cloudAccount?.continueInBrowser ? openSignIn() : setAdding(true)} />}
+ {!active && window.duskDesktop?.accounts && window.duskDesktop?.cloudAccount?.continueInBrowser ? openSignIn() : setAdding(true)} />}
{editing && (
setEditing(false)}>
@@ -413,7 +415,7 @@ function HelpGroup() {
setShortcuts(true)} />
void openExternalLink(HELP_CENTER_URL)} />
-
+ {window.duskDesktop?.exportDiagnostics && }
setAbout(false)} />
setShortcuts(false)} />
@@ -480,6 +482,7 @@ function AppsPage({ has }: { has: Has }) {
/** Grok's Usage & Billing pane: a card per engine limit, the Cloud's meters, then the breakdown and the plan as rows. */
export function UsagePane({ has, cloudAccount }: { has: Has; cloudAccount: ReactNode }) {
+ const selfHosted = useSelfHosted();
const { at } = useSubPage();
const { usage, upgrade, dialog } = useCloudUsageSettings();
const plan = useCloudPlan();
@@ -507,7 +510,7 @@ export function UsagePane({ has, cloudAccount }: { has: Has; cloudAccount: React
{(usage || has("usage")) && }
{usage &&
{dialog}
}
- {has("cloudAccount") && (
+ {selfHosted === false && has("cloudAccount") && (
@@ -550,6 +553,7 @@ function DataPage({ has }: { has: Has }) {
/** Models' top: the same grid of popular AIs as the first run and the Connect an AI dialog; its link goes to the
* directory just under it, and a connected AI's card to its accounts. */
function ConnectAiCards() {
+ const selfHosted = useSelfHosted();
const { state } = useStore();
const { open } = useSubPage();
const toDirectory = () => {
@@ -558,7 +562,8 @@ function ConnectAiCards() {
search?.focus({ preventScroll: true });
};
return (
-
+
+ {selfHosted && {t("selfHosted.providers.hint")}
}
{ const { page, title } = enginePageOf(state.instances, instance); open(page, title); }} />
diff --git a/src/components/SidebarProfileMenu.test.ts b/src/components/SidebarProfileMenu.test.ts
index 1fb648c330..0c0388e102 100644
--- a/src/components/SidebarProfileMenu.test.ts
+++ b/src/components/SidebarProfileMenu.test.ts
@@ -440,6 +440,32 @@ describe("grok's profile menu", () => {
accounts: { view: null, openSheet: undefined, signOut: vi.fn(), add: vi.fn() } as never,
};
+ it("hides irrelevant hosted account access on a self-hosted browser", () => {
+ const items = grokProfileMenuItems({ ...base, selfHosted: true, onDashboard: vi.fn() });
+ expect(items.map(item => item.key)).not.toContain("sign-in");
+ expect(items.map(item => item.key)).not.toContain("dashboard");
+ expect(items.map(item => item.key)).toContain("settings");
+ });
+
+ it("keeps an available dusk bot account connection explicitly optional", () => {
+ const add = vi.fn();
+ const items = grokProfileMenuItems({ ...base, selfHosted: true, accounts: { view: { active: null, others: [] }, openSheet: null, signOut: vi.fn(), add } as never });
+ const signIn = items.find(item => item.key === "sign-in")!;
+ expect(signIn.label).toBe("dusk bot account (optional)");
+ signIn.onSelect();
+ expect(add).toHaveBeenCalledOnce();
+ });
+
+ it("signs out the browser session without a hosted account bridge", () => {
+ const onServerSignOut = vi.fn();
+ const items = grokProfileMenuItems({ ...base, onServerSignOut });
+ expect(items.some(item => item.key === "sign-in")).toBe(false);
+ const row = items.find(item => item.key === "log-out");
+ expect(row?.label).toBe("Sign out");
+ row!.onSelect();
+ expect(onServerSignOut).toHaveBeenCalledOnce();
+ });
+
it("leads with the automation the avatar's red dot is for, so the dot always has somewhere to go", () => {
const onNeedsYou = vi.fn();
const items = grokProfileMenuItems({ ...base, onNeedsYou });
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index a14d0976df..6eeb4d0016 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -1,3 +1,5 @@
+import { useServerSignOut } from "./ServerSignOut";
+import { useSelfHosted } from "@/lib/use-self-hosted";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { AnimatePresence } from "motion/react";
import {
@@ -654,9 +656,11 @@ export interface MenuAccountHeader {
/** Grok's profile menu: the account (address and plan) first, then the phone app, the account dashboard, Support (help,
* shortcuts, about), Give feedback and Settings, and Sign out on its own last row. Everything else the menu once held is in Settings. */
-export function grokProfileMenuItems({ onGetApp, onHelp, onShortcuts, onFeedback, onAbout, onSettings, onAddAccount, onNeedsYou, onDashboard, accounts, header = null }: {
+export function grokProfileMenuItems({ onGetApp, onHelp, onShortcuts, onFeedback, onAbout, onSettings, onAddAccount, onNeedsYou, onDashboard, onServerSignOut, accounts, header = null, selfHosted = false }: {
/** the account block; this app's own page draws it from the account in use when none is given */
header?: MenuAccountHeader | null;
+ onServerSignOut?: () => void;
+ selfHosted?: boolean;
onAddAccount: () => void;
/** opens the hosted account dashboard for this workspace */
onDashboard?: () => void;
@@ -673,19 +677,20 @@ export function grokProfileMenuItems({ onGetApp, onHelp, onShortcuts, onFeedback
}): SidebarMenuItem[] {
const icon = (name: IconName) => ;
const active = accounts.view?.active;
- // signing out works here on this app's own page; anywhere else the sheet on the rail's page does it
- const signOut = active ? () => accounts.signOut(active.id) : accounts.openSheet;
+ const signOut = onServerSignOut ?? (active ? () => accounts.signOut(active.id) : accounts.openSheet);
const who: MenuAccountHeader | null = header ?? (active ? { name: active.name, email: active.email, plan: accountPlanText(active.plan), face: } : null);
const named = who?.name?.trim();
+ const accountAvailable = Boolean(accounts.view || accounts.openSheet || (typeof window !== "undefined" && window.duskDesktop?.cloudAccount));
+ const dashboard = !selfHosted || accountAvailable ? onDashboard : undefined;
const top: SidebarMenuItem[] = who
- ? [{ key: "who", label: named || who.email, ...(who.plan ? { labelNote: who.plan.replace(/^dusk cloud · /, "").replace(/ free trial$/, " trial") } : {}), title: who.email, ...(named ? { subtitle: who.email } : {}), icon: who.face, large: true, onSelect: onDashboard ?? accounts.openSheet ?? onSettings }]
+ ? [{ key: "who", label: named || who.email, ...(who.plan ? { labelNote: who.plan.replace(/^dusk cloud · /, "").replace(/ free trial$/, " trial") } : {}), title: who.email, ...(named ? { subtitle: who.email } : {}), icon: who.face, large: true, onSelect: dashboard ?? accounts.openSheet ?? onSettings }]
// nobody signed in here: Sign in, first, where the account would be; it continues in the browser for its context (the
// account context redirect), where this app can; otherwise the sheet that signs in right there
- : signOut ? [] : [{ key: "sign-in", label: t("accounts.signIn"), icon: icon("person"), onSelect: typeof window !== "undefined" && window.duskDesktop?.cloudAccount?.continueInBrowser ? () => openSignIn() : accounts.view ? () => accounts.add() : onAddAccount }];
+ : signOut || (selfHosted && !accountAvailable) ? [] : [{ key: "sign-in", label: t(selfHosted ? "selfHosted.account.optional" : "accounts.signIn"), icon: icon("person"), onSelect: typeof window !== "undefined" && window.duskDesktop?.cloudAccount?.continueInBrowser ? () => openSignIn() : accounts.view ? () => accounts.add() : onAddAccount }];
const last: SidebarMenuItem[] = signOut ? [{ key: "log-out", label: t("accounts.signOut"), icon: icon("arrow-bracket-from-left"), onSelect: signOut }] : [];
const menu: SidebarMenuItem[] = [
...(onGetApp ? [{ key: "mobile", label: t("sidebar.menu.connectPhone"), icon: icon("device-mobile"), onSelect: onGetApp } satisfies SidebarMenuItem] : []),
- ...(onDashboard ? [{ key: "dashboard", label: t("sidebar.menu.accountDashboard"), icon: icon("chart-bars"), onSelect: onDashboard } satisfies SidebarMenuItem] : []),
+ ...(dashboard ? [{ key: "dashboard", label: t("sidebar.menu.accountDashboard"), icon: icon("chart-bars"), onSelect: dashboard } satisfies SidebarMenuItem] : []),
{ key: "support", label: t("sidebar.grok.support"), icon: icon("book"), onSelect: () => {}, submenu: [
{ key: "help", label: t("sidebar.menu.help"), icon: icon("question-circle"), onSelect: onHelp },
{ key: "shortcuts", label: t("sidebar.menu.shortcuts"), icon: icon("keyboard"), onSelect: onShortcuts },
@@ -728,6 +733,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
/** grok folds the name away while the Connect apps pill widens beside it */
nameHidden?: boolean;
} = {}) {
+ const selfHosted = useSelfHosted();
const { state, dispatch } = useStore();
const simple = account !== undefined;
const [menuOpen, setMenuOpen] = useState(false);
@@ -752,6 +758,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
}, []);
const accounts = useAccounts();
+ const serverSignOut = useServerSignOut(session);
const sessionProfile = profileForSession(state.config?.profile, session);
const syncOwnAccount = localDesktopPage() && window.duskDesktop?.remoteClient?.active !== true && !state.config?.cloudHome && !state.config?.team;
useAccountName(syncOwnAccount, state.config?.profile, accounts.view?.active ?? null, dispatch);
@@ -783,6 +790,8 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
face: ,
} : null;
const grokItems = simple ? grokProfileMenuItems({
+ onServerSignOut: serverSignOut.request,
+ selfHosted: selfHosted !== false,
header,
onGetApp: phoneApp ? getApp : undefined,
onHelp: () => void openExternalLink(HELP_CENTER_URL),
@@ -816,7 +825,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
updateTop: simple ? simpleUpdateTop(update) : null,
move: move.items,
account: cloudAccount ? cloudRowLabel(accounts.view) : null,
- accounts: accountMenuItems(accounts),
+ accounts: serverSignOut.request ? [{ key: "server-sign-out", label: t("accounts.signOut"), icon: , onSelect: serverSignOut.request }] : accountMenuItems(accounts),
...(account ? { simple: {
tools: toolMenuItems({ archived: account.archived }),
places: placeMenuItems(account.place, { owner: account.owner, name: state.config?.team?.name, onCloudSettings: openCloudAccount }),
@@ -912,6 +921,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
setAboutOpen(false)} />
{accounts.sheet && }
{accounts.signOutConfirm}
+ {serverSignOut.dialog}
{accounts.picking && accounts.view?.active && }
{phoneAppOpen && {
- const { shown, onAdd } = await addRow({ app: { version: "1", ownPage: true }, workspaces: {} });
+ const { shown, onAdd } = await addRow({ app: { version: "1", ownPage: true }, workspaces: { add: vi.fn() } });
expect(shown).toBe(true);
expect(onAdd).toHaveBeenCalledTimes(1);
});
diff --git a/src/components/WorkspacesSettings.browser.test.ts b/src/components/WorkspacesSettings.browser.test.ts
new file mode 100644
index 0000000000..2265efab42
--- /dev/null
+++ b/src/components/WorkspacesSettings.browser.test.ts
@@ -0,0 +1,53 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, expect, it, vi } from "vitest";
+
+const f = vi.hoisted(() => ({ environment: null as any, current: null as any, places: [] as any[] }));
+vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: {} }, dispatch: vi.fn() }) }));
+vi.mock("@/lib/use-self-hosted", () => ({ useServerEnvironment: () => f.environment }));
+vi.mock("@/lib/places", () => ({ usePlaces: () => ({ places: f.places }), removePlace: vi.fn() }));
+vi.mock("./DesktopWorkspaceSwitcher", () => ({ useWorkspacePlace: () => ({ current: f.current }) }));
+vi.mock("@/lib/vps-cloud-move", () => ({ useVpsCloudMove: () => ({ view: null }) }));
+vi.mock("./CloudMoveSettings", () => ({ CloudMoveRow: () => null }));
+import { WorkspacesGroup } from "./WorkspacesSettings";
+const render = () => renderToStaticMarkup(createElement(WorkspacesGroup, { onAdd: vi.fn() }));
+afterEach(() => { delete window.duskDesktop; f.environment = null; f.current = null; f.places = []; });
+
+it("names the browser's server from its descriptor and offers no desktop workspace actions", () => {
+ f.environment = { label: "Research server", capabilities: { selfUpdate: "operator" } };
+ const html = render();
+ expect(html).toContain("Research server");
+ expect(html).toContain('data-workspace="server"');
+ expect(html).toContain("Your bots run on this server.");
+ expect(html).not.toContain("This computer");
+ expect(html).not.toContain("Click one to switch");
+ expect(html).not.toContain('data-settings-open="add-workspace"');
+});
+it("uses the browser hostname while the descriptor is unavailable", () => {
+ expect(render()).toContain(window.location.hostname);
+ expect(render()).not.toContain("This computer");
+});
+it("recognizes managed cloud in a browser without offering desktop-only setup", () => {
+ f.environment = { label: "Research cloud", capabilities: { cloudHome: true } };
+ const html = render();
+ expect(html).toContain('data-workspace="cloud"');
+ expect(html).toContain("Research cloud");
+ expect(html).not.toContain('data-settings-open="add-workspace"');
+});
+it("keeps desktop workspace labels, switching and adding available with their bridge", () => {
+ window.duskDesktop = { workspaces: { add: vi.fn(), open: vi.fn() }, app: { ownPage: true } } as never;
+ f.current = { local: true, name: "My workstation" };
+ f.places = [{ id: "local", name: "My workstation", kind: "computer", opens: true, active: true }, { id: "server", name: "Research server", kind: "server", opens: true }];
+ const html = render();
+ expect(html).toContain("My workstation");
+ expect(html).toContain("Research server");
+ expect(html).toContain("Click one to switch");
+ expect(html).toContain('data-settings-open="add-workspace"');
+});
+it("hides adding in desktop clients without that capability or on a remote workspace", () => {
+ window.duskDesktop = { workspaces: { open: vi.fn() }, app: { ownPage: true } } as never;
+ expect(render()).not.toContain('data-settings-open="add-workspace"');
+ window.duskDesktop = { workspaces: { add: vi.fn() }, app: { ownPage: false } } as never;
+ expect(render()).not.toContain('data-settings-open="add-workspace"');
+});
diff --git a/src/components/WorkspacesSettings.tsx b/src/components/WorkspacesSettings.tsx
index 062a08e9e2..8adb3c6cbd 100644
--- a/src/components/WorkspacesSettings.tsx
+++ b/src/components/WorkspacesSettings.tsx
@@ -1,3 +1,4 @@
+import { useServerEnvironment } from "@/lib/use-self-hosted";
import { useState } from "react";
import { useStore } from "@/state/store";
import { t } from "@/lib/i18n";
@@ -104,14 +105,17 @@ function WorkspaceRow({ place, onOpen, onRemove, busy }: { place: RailPlace; onO
export function WorkspacesGroup({ onAdd }: { onAdd: () => void }) {
const { state, dispatch } = useStore();
const rail = usePlaces();
+ const environment = useServerEnvironment();
+ const browser = !window.duskDesktop;
const here = useWorkspacePlace({ cloudHome: state.config?.cloudHome === true });
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const mine = rail.places[0]?.group;
const listed = rail.places.filter((place) => place.kind !== "account" && place.group === mine);
- const places: RailPlace[] = listed.length ? listed : [{
- id: "local", name: here.current?.name || kindWord(currentKind(here.current)), color: null, opens: true, active: true,
- kind: currentKind(here.current),
+ const kind = browser ? (environment?.capabilities.cloudHome || state.config?.cloudHome ? "cloud" : "server") : currentKind(here.current);
+ const name = browser ? environment?.label?.trim() || window.location.hostname : here.current?.name || kindWord(kind);
+ const places: RailPlace[] = !browser && listed.length ? listed : [{
+ id: "local", name, color: null, opens: true, active: true, kind,
}];
const hasCloud = places.some((place) => place.kind === "cloud" || place.kind === "team");
const canBuy = Boolean(window.duskDesktop?.cloudAccount) && window.duskDesktop?.remoteClient?.active !== true;
@@ -134,7 +138,7 @@ export function WorkspacesGroup({ onAdd }: { onAdd: () => void }) {
};
return (
-
+
{places.map((place) => (
open(place)}
@@ -145,7 +149,7 @@ export function WorkspacesGroup({ onAdd }: { onAdd: () => void }) {
onClick={() => dispatch({ type: "openCloudAdd", source: "app_settings" })} />
: serverMove ? } title={t("vpsMove.title")} hint={t("vpsMove.perk.server")} onClick={moveServer} />
: null} />
- {thisComputerPage() && } title={t("settings.docs.ws.add")} hint={t("settings.docs.ws.addHint")} onClick={onAdd} />}
+ {thisComputerPage() && window.duskDesktop?.workspaces?.add && } title={t("settings.docs.ws.add")} hint={t("settings.docs.ws.addHint")} onClick={onAdd} />}
{(error || here.error) && {error || here.error} }
diff --git a/src/lib/session.test.ts b/src/lib/session.test.ts
index b4eb89890a..138217e847 100644
--- a/src/lib/session.test.ts
+++ b/src/lib/session.test.ts
@@ -1,3 +1,4 @@
+import { signOutServerSession } from "./session";
import { describe, expect, it, vi } from "vitest";
import {
@@ -183,3 +184,15 @@ describe("an SSH tunnel to a server that treats local requests as a service", ()
expect(reasonWorthShowing(SERVICE_TRUST_REASON)).toBe(SERVICE_TRUST_REASON);
});
});
+
+describe("server session sign-out", () => {
+ it("revokes the current cookie session through the server", async () => {
+ const request = vi.fn(async () => new Response('{"ok":true}', { status: 200 }));
+ await signOutServerSession(request);
+ expect(request).toHaveBeenCalledWith("/api/auth/logout", { method: "POST", credentials: "same-origin" });
+ });
+ it("does not report success when the server refuses or cannot be reached", async () => {
+ await expect(signOutServerSession(vi.fn(async () => new Response(null, { status: 503 })))).rejects.toThrow("503");
+ await expect(signOutServerSession(vi.fn(async () => { throw new Error("offline"); }))).rejects.toThrow("offline");
+ });
+});
diff --git a/src/lib/session.ts b/src/lib/session.ts
index e1db6eca23..7f2fe48b47 100644
--- a/src/lib/session.ts
+++ b/src/lib/session.ts
@@ -6,7 +6,7 @@ export interface EnvironmentDescriptor {
label: string;
platform: string;
version: string;
- capabilities: { api?: number; remoteSessions: true; selfUpdate: "desktop-managed" | "operator"; emailSignIn?: boolean; cloudHome?: true; cloudTeam?: true };
+ capabilities: { api?: number; remoteSessions: true; selfUpdate: "desktop-managed" | "operator"; emailSignIn?: boolean; passwordSignIn?: boolean; cloudHome?: true; cloudTeam?: true };
}
/** A Team Cloud's session: the team and this person's role in it (owner, admin or member). */
@@ -82,6 +82,11 @@ function teamSessionOf(value: unknown): TeamSession | null {
export const SERVICE_TRUST_REASON = "this server does not treat this computer as its owner. sign in or pair this browser to continue.";
+export async function signOutServerSession(fetchImpl: typeof fetch = fetch): Promise {
+ const response = await fetchImpl("/api/auth/logout", { method: "POST", credentials: "same-origin" });
+ if (!response.ok) throw new Error(`Sign out failed (${response.status})`);
+}
+
export function isConnected(state: SessionState | null): boolean {
return state?.kind === "session" || (state?.kind === "loopback" && state.trust !== "service");
}
@@ -203,3 +208,7 @@ export function reasonWorthShowing(reason: string | undefined): string | null {
if (/through a proxy|loopback host required|cross-origin request|this browser is not signed in|^40[13]$/i.test(reason)) return null;
return reason;
}
+
+export function signInWithPassword(input: { email: string; password: string; label: string }, fetchImpl: typeof fetch = fetch): Promise<{ ok: true } | { ok: false; error: string }> {
+ return postAuth("/api/auth/password", input, fetchImpl);
+}
diff --git a/src/lib/use-self-hosted.test.ts b/src/lib/use-self-hosted.test.ts
new file mode 100644
index 0000000000..f3bd920604
--- /dev/null
+++ b/src/lib/use-self-hosted.test.ts
@@ -0,0 +1,54 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { EnvironmentDescriptor } from "./session";
+
+let root: Root | null;
+let seen: (boolean | null)[];
+beforeEach(() => {
+ vi.resetModules(); vi.useFakeTimers(); seen = []; root = null;
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+});
+afterEach(() => {
+ act(() => root?.unmount()); vi.useRealTimers(); vi.unstubAllGlobals();
+});
+const descriptor = (capabilities = {}) => ({ environmentId: "fixture", label: "Fixture server", version: "1", platform: "linux", capabilities: { remoteSessions: true, selfUpdate: "operator", ...capabilities } }) as EnvironmentDescriptor;
+async function mount() {
+ const { useSelfHosted } = await import("./use-self-hosted");
+ function Probe() { seen.push(useSelfHosted()); return null; }
+ root = createRoot(document.createElement("div"));
+ await act(async () => root!.render(createElement(Probe)));
+}
+it("detects operator hosting without confusing desktop or managed cloud", async () => {
+ const { isSelfHosted } = await import("./use-self-hosted");
+ expect(isSelfHosted(descriptor())).toBe(true);
+ expect(isSelfHosted(descriptor({ cloudHome: true }))).toBe(false);
+ expect(isSelfHosted(descriptor({ cloudHome: true, cloudTeam: true }))).toBe(false);
+ expect(isSelfHosted(descriptor({ selfUpdate: "desktop-managed" }))).toBe(false);
+ expect(isSelfHosted(null)).toBe(false);
+});
+it("shares a resolved descriptor across mounted consumers", async () => {
+ const fetch = vi.fn(async () => new Response(JSON.stringify(descriptor())));
+ vi.stubGlobal("fetch", fetch);
+ await mount();
+ expect(seen).toEqual([null, true]);
+ act(() => root?.unmount()); await mount();
+ expect(seen.at(-1)).toBe(true); expect(fetch).toHaveBeenCalledOnce();
+});
+it("keeps detection pending after an outage, retries, and cancels retries when unused", async () => {
+ const fetch = vi.fn().mockRejectedValueOnce(new TypeError("offline"))
+ .mockResolvedValue(new Response(JSON.stringify(descriptor({ cloudHome: true }))));
+ vi.stubGlobal("fetch", fetch);
+ await mount(); expect(seen).toEqual([null]);
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ expect(seen.at(-1)).toBe(false); expect(fetch).toHaveBeenCalledTimes(2);
+ act(() => root?.unmount()); root = null;
+ await vi.advanceTimersByTimeAsync(30_000); expect(fetch).toHaveBeenCalledTimes(2);
+});
+it("stops scheduling retries after the last consumer leaves", async () => {
+ const fetch = vi.fn().mockResolvedValue(new Response("unavailable", { status: 503 }));
+ vi.stubGlobal("fetch", fetch); await mount();
+ act(() => root?.unmount()); root = null;
+ await vi.advanceTimersByTimeAsync(30_000); expect(fetch).toHaveBeenCalledOnce();
+});
diff --git a/src/lib/use-self-hosted.ts b/src/lib/use-self-hosted.ts
new file mode 100644
index 0000000000..9e504ab2db
--- /dev/null
+++ b/src/lib/use-self-hosted.ts
@@ -0,0 +1,44 @@
+import { useSyncExternalStore } from "react";
+import type { EnvironmentDescriptor } from "./session";
+
+export function isSelfHosted(environment: EnvironmentDescriptor | null): boolean {
+ return environment?.capabilities.selfUpdate === "operator" && !environment.capabilities.cloudHome;
+}
+
+let known: EnvironmentDescriptor | null = null;
+let looking = false;
+let retry: ReturnType | null = null;
+const listeners = new Set<() => void>();
+
+function lookUp() {
+ retry = null;
+ if (known !== null || looking || !listeners.size) return;
+ looking = true;
+ void fetch("/.well-known/duskbot/environment")
+ .then(async response => response.ok ? await response.json() as EnvironmentDescriptor : null)
+ .then(environment => { if (environment) known = environment; })
+ .catch(() => {})
+ .finally(() => {
+ looking = false;
+ for (const listener of listeners) listener();
+ if (known === null && listeners.size) retry = setTimeout(lookUp, 10_000);
+ });
+}
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ if (!retry) lookUp();
+ return () => {
+ listeners.delete(listener);
+ if (!listeners.size && retry) { clearTimeout(retry); retry = null; }
+ };
+}
+
+export function useServerEnvironment(): EnvironmentDescriptor | null {
+ return useSyncExternalStore(subscribe, () => known, () => null);
+}
+
+export function useSelfHosted(): boolean | null {
+ const environment = useServerEnvironment();
+ return environment === null ? null : isSelfHosted(environment);
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index a004269c87..cd32080ec5 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1,4 +1,15 @@
{
+ "selfHosted.phone.hint": "dusk bot on your phone talks to the bots on this server.",
+ "selfHosted.computer.title": "This server",
+ "selfHosted.pairing.code": "This server's code",
+ "selfHosted.workspace.hint": "Your bots run on this server.",
+ "serverSignOut.title": "Sign out of this server?",
+ "serverSignOut.body": "This browser will need to sign in again. Your bots and connected AI providers will keep running.",
+ "serverSignOut.failed": "Could not sign out. Please try again.",
+ "selfHosted.account.optional": "dusk bot account (optional)",
+ "selfHosted.account.hint": "Separate from your sign-in to this server.",
+ "selfHosted.providers.optional": "AI provider connections (optional)",
+ "selfHosted.providers.hint": "Connect the providers you want your bots to use. These accounts do not sign you into this server.",
"updates.updated": "Updated to {version}",
"updates.rolledBack": "Update rolled back, nothing lost",
"appUpdate.restart": "Restart to update",
@@ -3588,6 +3599,7 @@
"settings.w6a.browser.windows": "Not available on Windows yet",
"settings.w6a.browser.hint": "Lets your bots open websites in a browser of their own.",
"settings.w6a.browser.notInstalled": "Not installed yet. Install it from a bot's browser.",
+ "selfHosted.browser.serverSitesDetail": "Includes this server’s local network",
"settings.w6a.browser.serverSitesDetail": "Includes your local network",
"settings.w6a.connect": "Connect",
"settings.w6a.setUp": "Set up",
diff --git a/src/pair/PairPage.test.ts b/src/pair/PairPage.test.ts
index 323081c9d6..41af783517 100644
--- a/src/pair/PairPage.test.ts
+++ b/src/pair/PairPage.test.ts
@@ -65,6 +65,7 @@ it("a team's Cloud is called by the team's name, a person's own Cloud My Cloud",
const descriptor = (capabilities: Record) => ({ environmentId: "e", label: "Acme Labs", platform: "linux", version: "1", capabilities: { remoteSessions: true as const, selfUpdate: "operator" as const, ...capabilities } });
expect(pairTitle(descriptor({ cloudHome: true, cloudTeam: true }), "code")).toBe("Acme Labs");
expect(pairTitle(descriptor({ cloudHome: true }), "code")).toBe("My cloud");
+ expect(pairTitle(descriptor({}), "code")).toBe("Sign in to Acme Labs");
expect(pairTitle(descriptor({}), "email")).toBe("Sign in to Acme Labs");
expect(pairTitle(null, "code")).toBe("Connect to this dusk bot");
});
diff --git a/src/pair/PairPage.tsx b/src/pair/PairPage.tsx
index 064c94b804..630bae2d8e 100644
--- a/src/pair/PairPage.tsx
+++ b/src/pair/PairPage.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import { DesktopWorkspaceSwitcher } from "../components/DesktopWorkspaceSwitcher";
+import { isSelfHosted } from "../lib/use-self-hosted";
import { productName } from "../lib/brand";
import {
@@ -10,6 +11,7 @@ import {
readSessionState,
reasonWorthShowing,
startEmailSignIn,
+ signInWithPassword,
verifyEmailSignIn,
type EnvironmentDescriptor,
type SessionState,
@@ -25,7 +27,8 @@ export function pairsAutomatically(initialCode: string | null, desktop = typeof
return Boolean(initialCode) && desktop;
}
-export function pairIntro({ mode, sent, email, cloudHome }: { mode: "email" | "code" | null; sent: boolean; email: string; cloudHome: boolean }): string {
+export function pairIntro({ mode, sent, email, cloudHome }: { mode: "email" | "code" | "password" | null; sent: boolean; email: string; cloudHome: boolean }): string {
+ if (mode === "password") return "Enter the email and password set by this server’s owner.";
if (mode === "email") return sent ? `We emailed an 8-digit code to ${email}. It works once and expires in ten minutes.` : "Enter your email and we will send you a one-time code.";
if (cloudHome) return `To open the cloud, choose Open the cloud in the ${productName()} app on your computer (Settings → dusk cloud), or use in your browser on your plan page. Have a pairing code? Enter it below.`;
return "Enter the pairing code shown on the server. Codes work once and expire after five minutes.";
@@ -38,10 +41,11 @@ export function inIphoneTab(nav: { userAgent: string; standalone?: boolean } | u
export const IPHONE_HOME_SCREEN_HINT = `On iPhone, the ${productName()} app from the App Store is the easy way. To use this page from your Home Screen instead, add it first (Share, then Add to Home Screen), open it from there and enter the code. The Home Screen copy keeps its own sign-in, so a code used in this tab won't carry over.`;
-export function pairTitle(environment: EnvironmentDescriptor | null, mode: "email" | "code" | null): string {
+export function pairTitle(environment: EnvironmentDescriptor | null, mode: "email" | "code" | "password" | null): string {
+ if (isSelfHosted(environment)) return `Sign in to ${environment!.label}`;
if (environment?.capabilities.cloudTeam) return environment.label;
if (environment?.capabilities.cloudHome) return "My cloud";
- return `${mode === "email" ? "Sign in to" : "Connect to"} ${environment?.label ?? `this ${productName()}`}`;
+ return `${mode !== "code" ? "Sign in to" : "Connect to"} ${environment?.label ?? `this ${productName()}`}`;
}
export function PairPage({ initialCode, initialEmail = null, reason }: { initialCode: string | null; initialEmail?: string | null; reason?: string }) {
@@ -52,8 +56,9 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [attemptId, setAttemptId] = useState(() => newAttemptId());
- const [mode, setMode] = useState<"email" | "code" | null>(initialCode ? "code" : null);
+ const [mode, setMode] = useState<"email" | "code" | "password" | null>(initialCode ? "code" : null);
const [email, setEmail] = useState(initialEmail ?? "");
+ const [password, setPassword] = useState("");
const [otp, setOtp] = useState("");
const [sent, setSent] = useState(false);
const [opening, setOpening] = useState(() => pairsAutomatically(initialCode));
@@ -76,7 +81,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
.then((r) => (r.ok ? r.json() : null))
.then((d: EnvironmentDescriptor | null) => {
setEnvironment(d);
- setMode((current) => current ?? (d?.capabilities.emailSignIn ? "email" : "code"));
+ setMode((current) => current ?? (d?.capabilities.passwordSignIn ? "password" : d?.capabilities.emailSignIn ? "email" : "code"));
})
.catch(() => {
setEnvironment(null);
@@ -86,6 +91,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
}, []);
const connected = isConnected(session);
+ const passwordOffered = environment?.capabilities.passwordSignIn === true;
const emailOffered = environment?.capabilities.emailSignIn === true;
const cloudHome = environment?.capabilities.cloudHome === true;
@@ -106,21 +112,25 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
e.preventDefault();
setBusy(true);
setError(null);
- const result = sent ? await verifyEmailSignIn({ email, code: otp, label }) : await startEmailSignIn(email);
+ const result = mode === "password" ? await signInWithPassword({ email, password, label }) : sent ? await verifyEmailSignIn({ email, code: otp, label }) : await startEmailSignIn(email);
+ setPassword("");
setBusy(false);
if (!result.ok) {
setError(result.error);
return;
}
- if (sent) {
+ if (sent || mode === "password") {
location.replace(pairedDestination(location.search));
return;
}
setSent(true);
}
- function switchMode(next: "email" | "code") {
+ function switchMode(next: "email" | "code" | "password") {
setMode(next);
+ setPassword("");
+ setOtp("");
+ setSent(false);
setError(null);
}
@@ -136,6 +146,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
{environment && !cloudHome ? `Version ${environment.version} on ${environment.platform}. ` : ""}
{pairIntro({ mode, sent, email, cloudHome })}
+ {isSelfHosted(environment) && !connected && This signs you into this server. Optional dusk bot accounts and AI provider connections are managed after sign-in.
}
{inIphoneTab() && !connected ? {IPHONE_HOME_SCREEN_HINT}
: null}
{reasonWorthShowing(reason) && !connected ? {reasonWorthShowing(reason)}
: null}
{error && cloudHome && initialCode ? This link has expired or was already used. In the {productName()} app on your computer, open Settings → dusk cloud and choose Open the cloud.
: null}
@@ -147,7 +158,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial
Open the app
- ) : mode === "email" ? (
+ ) : mode === "email" || mode === "password" ? (