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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/self-hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<data dir>/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
Expand Down
3 changes: 3 additions & 0 deletions docs/verification/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,9 @@ 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.

## Evidence

The [Gemini speech fixture](gemini-speech.md) checks write-only credentials,
Expand Down
46 changes: 46 additions & 0 deletions docs/verification/local-passwords.md
Original file line number Diff line number Diff line change
@@ -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=<git ref>` 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
```
13 changes: 13 additions & 0 deletions scripts/testing/password-signin-preview.tsx
Original file line number Diff line number Diff line change
@@ -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(<Component initialCode={null} />);
95 changes: 95 additions & 0 deletions scripts/testing/password-signin.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof connect>> | 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);
72 changes: 72 additions & 0 deletions server/account-signin-routes.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> => {
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;
};
}
Loading