From 2674ccc793b8995591f388311711975530890c41 Mon Sep 17 00:00:00 2001 From: Akash A <82976966+akashanil-dev@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:16:18 +0530 Subject: [PATCH 1/4] Add server-managed local password sign-in for self-hosted workspaces --- docs/self-hosting.md | 31 +++ docs/verification/local-passwords.md | 31 +++ scripts/testing/password-signin-preview.tsx | 13 ++ scripts/testing/password-signin.e2e.test.ts | 81 +++++++ server/account-signin-routes.ts | 72 +++++++ server/cli-access.ts | 96 +++++++++ server/cli-password.test.ts | 60 ++++++ server/cli-usage.ts | 4 +- server/cli.test.ts | 4 +- server/cli.ts | 84 +------- server/cloud-team-policy.ts | 2 +- server/environment.ts | 5 +- server/index.ts | 50 +---- server/password-signin.test.ts | 227 ++++++++++++++++++++ server/passwords.test.ts | 94 ++++++++ server/passwords.ts | 75 +++++++ server/sessions.ts | 12 +- server/workspace-backup-policy.ts | 2 +- src/lib/session.ts | 6 +- src/pair/PairPage.tsx | 41 ++-- 20 files changed, 854 insertions(+), 136 deletions(-) create mode 100644 docs/verification/local-passwords.md create mode 100644 scripts/testing/password-signin-preview.tsx create mode 100644 scripts/testing/password-signin.e2e.test.ts create mode 100644 server/account-signin-routes.ts create mode 100644 server/cli-access.ts create mode 100644 server/cli-password.test.ts create mode 100644 server/password-signin.test.ts create mode 100644 server/passwords.test.ts create mode 100644 server/passwords.ts diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 9813fc00a3..b90463a7ad 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -601,6 +601,37 @@ 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. + +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/local-passwords.md b/docs/verification/local-passwords.md new file mode 100644 index 0000000000..79e76c8f1b --- /dev/null +++ b/docs/verification/local-passwords.md @@ -0,0 +1,31 @@ +# 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. +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. 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. 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..3f00379401 --- /dev/null +++ b/scripts/testing/password-signin.e2e.test.ts @@ -0,0 +1,81 @@ +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", "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"] }); + writeFileSync(join(evidence, "verified.json"), JSON.stringify({ passwordLogin: true, wrongPasswordRefused: true, cookieSession: session.kind, 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/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 ({ 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/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/lib/session.ts b/src/lib/session.ts index e1db6eca23..6bd1e0d110 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). */ @@ -203,3 +203,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/pair/PairPage.tsx b/src/pair/PairPage.tsx index 064c94b804..7bf1aef01e 100644 --- a/src/pair/PairPage.tsx +++ b/src/pair/PairPage.tsx @@ -10,6 +10,7 @@ import { readSessionState, reasonWorthShowing, startEmailSignIn, + signInWithPassword, verifyEmailSignIn, type EnvironmentDescriptor, type SessionState, @@ -25,7 +26,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 +40,10 @@ 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 (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 +54,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 +79,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 +89,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 +110,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); } @@ -147,7 +155,7 @@ export function PairPage({ initialCode, initialEmail = null, reason }: { initial Open the app

- ) : mode === "email" ? ( + ) : mode === "email" || mode === "password" ? (