From 0de5a335030def0fa5d6d86c53c13c8ec2f20a57 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 03:16:44 +0900 Subject: [PATCH 01/16] Add standalone Owner password sign-in for Remote Hosts Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- .../features/remote-hosts.md | 8 + GLOSSARY.md | 4 + GLOSSARY.zh.md | 4 + changes/4898-owner-remote-sign-in.md | 11 + .../botharness-architecture.en.md | 6 + docs/architecture/botharness-architecture.md | 6 + docs/bot-cli.md | 4 + docs/bot-cli.zh.md | 4 + docs/decisions/connections.md | 16 ++ docs/decisions/team-mode.md | 14 + .../src/client/bot-settings-sections.tsx | 5 +- .../client/client-settings-registration.ts | 2 +- .../client/src/client/connections-dialog.tsx | 4 + .../environments/connections-locale.ts | 20 ++ .../environments/remote-host-browser.ts | 1 + .../environments/remote-host-pairing.ts | 71 ++++- .../client/src/client/features/team/locale.ts | 14 +- packages/client/src/client/host-tabs.tsx | 19 ++ .../owner-password-sign-in-settings.tsx | 253 ++++++++++++++++++ .../src/client/owner-sign-in-dialog.tsx | 135 ++++++++++ packages/client/src/client/paired-devices.tsx | 7 + packages/client/src/client/remote-hosts.ts | 13 +- .../owner-password-sign-in-settings.test.tsx | 151 +++++++++++ .../client/test/owner-sign-in-dialog.test.tsx | 63 +++++ packages/core/src/bots/cli-device-client.ts | 64 ++++- packages/core/src/bots/cli-effects.ts | 5 + packages/core/src/bots/cli-live-dispatch.ts | 2 +- packages/core/src/bots/cli-team.ts | 17 +- packages/core/src/bridge/rpc.ts | 8 + packages/core/src/database/schema-plan.ts | 15 ++ .../core/src/devices/encrypted-gateway.ts | 27 +- packages/core/src/devices/gateway.ts | 34 +-- packages/core/src/devices/pairing.ts | 60 ++++- packages/core/src/devices/route-context.ts | 16 ++ packages/core/src/features/team/rpc.ts | 13 + packages/core/src/team/bridge.ts | 16 ++ packages/core/src/team/devices.ts | 14 + packages/core/src/team/service.ts | 89 +++++- packages/core/test/cli-device-client.test.ts | 38 ++- packages/core/test/cli-team.test.ts | 27 ++ .../owner-password-device-sign-in.test.ts | 182 +++++++++++++ packages/host-client/src/client.ts | 4 +- packages/host-client/src/encrypted-carrier.ts | 30 ++- packages/host-client/src/encrypted-sign-in.ts | 94 +++++++ packages/host-client/src/hosts.ts | 4 +- packages/host-client/src/owner-sign-in.ts | 134 ++++++++++ packages/host-client/src/team-client.ts | 101 +------ .../host-client/test/owner-sign-in.test.ts | 193 +++++++++++++ packages/host-protocol/src/carrier.ts | 1 + packages/host-protocol/src/host-encryption.ts | 1 + packages/host-protocol/src/route.ts | 15 +- scripts/cli-ui-inventory.json | 9 + scripts/schema-migrations.json | 4 + 53 files changed, 1894 insertions(+), 158 deletions(-) create mode 100644 changes/4898-owner-remote-sign-in.md create mode 100644 packages/client/src/client/owner-password-sign-in-settings.tsx create mode 100644 packages/client/src/client/owner-sign-in-dialog.tsx create mode 100644 packages/client/test/owner-password-sign-in-settings.test.tsx create mode 100644 packages/client/test/owner-sign-in-dialog.test.tsx create mode 100644 packages/core/test/owner-password-device-sign-in.test.ts create mode 100644 packages/host-client/src/encrypted-sign-in.ts create mode 100644 packages/host-client/src/owner-sign-in.ts create mode 100644 packages/host-client/test/owner-sign-in.test.ts diff --git a/.agents/skills/verify-deepseekbot/features/remote-hosts.md b/.agents/skills/verify-deepseekbot/features/remote-hosts.md index 581673f6c0..9dd1557e04 100644 --- a/.agents/skills/verify-deepseekbot/features/remote-hosts.md +++ b/.agents/skills/verify-deepseekbot/features/remote-hosts.md @@ -16,6 +16,14 @@ The browser reads each Remote Host Feed through its own Paired Device and the sh - Paired Device - Host Relationship +## Standalone Owner password sign-in (#4898) + +Use two fresh Profiles on the same build. Serve the target Host's device channel over a trusted HTTPS origin. For two Hosts on one machine, keep the source Web Client and target HTTPS gateway on different hostnames so their cookies stay scoped to their own hostnames. + +With Team mode off, open the target Host's Connections settings. Turn on **Password sign-in** and set an Owner username and password. In the source Owner Client, open **Add remote**, choose password sign-in, and enter the HTTPS address and credentials. Open a Channel unique to the target Host. Compare the visible Channel with the target CLI roster and the new exact device record. Check wrong credentials and an invalid or changed Host identity before the successful attempt. Record a clean console and an accessibility snapshot without credential fields. + +Use `team-mode owner-sign-in status` to inspect the setting. Sign in a separate CLI device with `device-owner-sign-in` and validate `device-probe` with its private device file. Disable password sign-in on the target. Verify that a new login is refused and both enrolled devices still read the target Feed. Revoke the CLI device by its ID and verify it loses access. Restart the target Profile and verify the setting and selected username persist. Remove test device files during cleanup. + ## Reciprocal relationship (E1) Use fresh schema144 Homes after published Team141–143; do not launch internal Environment141–143 preview databases with this source. Relationship management is current-Owner-only: member/Admin HTTP carriers and CLI `--as` must refuse list/initiate/approve/enroll/disconnect. Transfer Owner and require old derived credentials and pending old-Owner offers to refuse; a newly enrolled Client records the new Owner Human. A valid current-Owner credential still cannot bypass inactive-relationship admission. Retain private Source Event Human readback, spoofed Human rejection and private-Bot access refusals through the same per-Human bridge factory. diff --git a/GLOSSARY.md b/GLOSSARY.md index 898ea1b9cd..5d9a5245c4 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -1150,6 +1150,10 @@ _Avoid_: Computer, other computer, machine, server, peer A client, a phone app or one browser profile on one origin, holding its own revocable credential from one Host. It reads and acts on that Host as exactly one Human ID but never hosts PersonaBots or relays another Host. _Avoid_: phone (for all devices), session, Host +**Host sign-in link**: +A Host-generated link or QR code that supplies the Host route and identity fingerprint for password sign-in. The Human supplies their own Member Credential. +_Avoid_: pairing offer, device grant + **Host Relationship**: A durable, explicitly authorized bidirectional relationship between two Hosts from which supported Clients obtain their own independent device grants. It is distinct from account registration, a connection route, an individual device grant and Bot Collaboration Network membership. _Avoid_: shared remote credential, Host Feed mirror, Bot collaboration admission diff --git a/GLOSSARY.zh.md b/GLOSSARY.zh.md index 4ae72986f5..1d5682ffc9 100644 --- a/GLOSSARY.zh.md +++ b/GLOSSARY.zh.md @@ -1149,6 +1149,10 @@ _避免使用_:Computer、其它电脑、machine、server、peer 持有某台 Host 发放的独立、可撤销凭据的客户端:一个手机 App,或一个 origin 上的一个浏览器 profile。它以唯一一个 Human ID 的身份读取并操作那台 Host,但从不承载 PersonaBot,也不中转其它 Host。 _避免使用_:phone(指所有设备时)、session、Host +**Host sign-in link**: +界面中文为“Host 登录链接”。由 Host 生成的链接或二维码,提供账密登录所需的 Host 线路和身份指纹。Human 使用自己的 Member Credential 登录。 +_避免使用_:配对邀请、设备授权 + **Host Relationship**: 两个 Host 之间持久且明确授权的双向关系,支持的 Client 据此取得各自独立的设备授权。它不同于账号注册、连接线路、单个设备授权或 Bot Collaboration Network 成员资格。 _避免使用_:共享远程凭据、Host Feed 镜像、Bot 协作准入 diff --git a/changes/4898-owner-remote-sign-in.md b/changes/4898-owner-remote-sign-in.md new file mode 100644 index 0000000000..c74071a124 --- /dev/null +++ b/changes/4898-owner-remote-sign-in.md @@ -0,0 +1,11 @@ +--- +section: Added +--- + +## en + +- Host Owners can enable password sign-in for desktop and Web Clients that connect to their Host over trusted HTTPS, including when Team mode is off. Existing QR pairing remains available ([#4898](https://github.com/BotHarness/DeepSeekBot/issues/4898)). + +## zh + +- Host Owner 可开启账密登录,让桌面和 Web 客户端通过可信 HTTPS 连接自己的 Host。关闭团队模式时也可单独开启,原有扫码配对仍可使用([#4898](https://github.com/BotHarness/DeepSeekBot/issues/4898))。 diff --git a/docs/architecture/botharness-architecture.en.md b/docs/architecture/botharness-architecture.en.md index b842a5d960..66adfe9e23 100644 --- a/docs/architecture/botharness-architecture.en.md +++ b/docs/architecture/botharness-architecture.en.md @@ -66,6 +66,12 @@ Welcome messages kept from earlier versions still offer capability introduction, Native model and credential Services remain authoritative. Default-on Profile setup saves and verifies the native global selection, leaving the Bot inheriting; opting out writes an individual Model Plan. New Bots without a plan follow the global default. A retained revision counter protects return to inheritance; global edits preserve fixed plans and running Assignment Sessions. Manual retry uses the original Human message and Admission through the existing retryability/side-effect gate, without adding another Human message. +## Accepted target for Remote Host password sign-in + +Desktop, iOS, and Android share the Host identity and password sign-in flow when adding a Remote Host. The application-defined Team Service owns the Host's sign-in policy and Member Credentials. The Client uses a saved key, an independently verified fingerprint, a Host sign-in link, or a trusted HTTPS origin to establish trust in the Host key. It submits credentials through the device gateway's Noise channel, which can also run over a tunnel or an HTTP-only LAN. + +The Host issues a Paired Device grant for the authenticated Human and binds it to the Client device key. The existing Devices module owns the grant and records its issuance method for selective revocation during Owner password changes. Team mode enables password sign-in. With Team mode off, the standalone Owner setting controls new Owner password sign-ins. The first delivery covers standalone Owner sign-in over HTTPS in desktop and Web Clients. See [connection decisions](../decisions/connections.md#remote-host-password-sign-in-uses-the-same-encrypted-device-channel-on-every-route) and [Team mode decisions](../decisions/team-mode.md#host-password-sign-in-and-team-mode). + ## 1 · System context ```mermaid diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md index 0c3e1b885c..9007d80a7e 100644 --- a/docs/architecture/botharness-architecture.md +++ b/docs/architecture/botharness-architecture.md @@ -654,6 +654,12 @@ The application-defined `ConnectionsDialog` presents pairing and device manageme 托管 Connect 在既有路由列表增加 Cloudflare Tunnel。WorkOS 与中继只负责发现 Host、签发绑定账号和 verifier 的配对请求;它们不能授予设备权限。依照 [ADR-0244](../decisions/connections.md#adr-0244),手机或可信本机浏览器先独立核对 Host 指纹,再由 Host 批准准确的设备公钥。Connect origin 只开放公开身份元数据及加密通道,不接受明文应用调用。大陆可达性、原生设备和实际云端发布分别验收。 +#### Remote Host 账密登录(已接受设计,逐片交付) + +桌面、iOS 和 Android 在添加 Remote Host 时共用 Host 身份验证与账密登录流程。应用定义的 Team Service 持有 Host 登录策略和 Member Credential。客户端根据已固定的公钥、独立核对的指纹、Host 登录链接或可信 HTTPS 来源验证 Host,再通过设备网关的 Noise 通道提交账密。Cloudflare Tunnel、Tailscale 和内网 HTTP 都可承载这条通道。 + +Host 按当前 Human 身份签发与客户端设备公钥绑定的 Paired Device 授权。设备授权由现有设备模块持有,并记录签发方式,供 Owner 改密时选择性撤销。Team mode 自动开启账密登录。Team mode 关闭后,Host 根据独立的 Owner 设置决定是否接收新的 Owner 账密登录。见[连接决策](../decisions/connections.md#remote-host-password-sign-in-uses-the-same-encrypted-device-channel-on-every-route)和 [Team mode 决策](../decisions/team-mode.md#host-password-sign-in-and-team-mode)。 + ### 手机推送 [ADR-0202](../decisions/mobile.md#adr-0202)([#1655](https://github.com/BotHarness/DeepSeekBot/issues/1655)):应用定义的 Push delivery 模块(`packages/core/src/push/`)是 Activity 的投影,不另设通知权威。Activity 表或 PersonaBot 的审批、提问、私密输入计数变化时(以及每分钟一次的兜底扫描),模块读取 `action` 项与未读的 `replies` 项,对每台已登记的配对设备只发送一次新项,并经 Expo Push Service 投递;推送标题为频道名(`#名称`,私信为 PersonaBot 名称),正文为所需操作加上工具与主要参数、问题或消息的简短预览(折叠空白,预览最多 140 个 UTF-16 代码单元,含截断省略号);私密输入请求不含内容([ADR-0213](../decisions/mobile.md#adr-0213))。数据字段包含路由标识、显示文字及适用的发送者和审批元数据。由 Android 原生模块呈现的通知也从数据字段读取标题、正文和角标。角标表示该 Host 的未处理 Human 操作数。设备经设备网关的 `/botharness-device/push` 登记 Expo push token、切换各类通知、发送测试通知;撤销设备或 Expo 回报 `DeviceNotRegistered` 时删除 token。发送失败有界重试,结果写入不含内容的 `push` 开发者日志。App 保存每台配对的 Host,点按通知先切换到对应 Host,再打开该审批、提问或私信。 diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 11cdf24d90..143633aa5b 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -2256,6 +2256,10 @@ QQ also supports `deepseekbot messaging-defaults qq` and `messaging-defaults-set ### Team mode and Host Members +Use `team-mode owner-sign-in status` to read the standalone Owner sign-in setting on the selected Host. To create the first credential, run `team-mode owner-sign-in on --username --password-stdin --confirm` with the password on stdin. To reuse a configured credential, run `team-mode owner-sign-in on --confirm`. The `off` action stops new password sign-ins and keeps existing Owner devices connected. + +On another Client, use `device-owner-sign-in --password-stdin --confirm --out `. The CLI validates the HTTPS origin and sends the password through the authenticated encrypted device channel. It writes keys and credentials to the new private file and prints the Host ID, device ID, and output path. Use `device-probe --device-file ` to read the real Host Feed with that device grant. + `dm ` opens or creates the authenticated Human's canonical DM with that active person on the selected Host. Opening from either participant returns the same Channel; another Human's DM remains inaccessible. Use `channels send --body-stdin` and `channel-messages ` for messages. Pure Human DMs have no Bot participant; Group messages remain readable by their eligible Bot members. The Owner CLI also accepts private LAN IPv4 HTTPS origins with normal certificate verification. Plain LAN HTTP remains refused. A private test CA can be supplied through the machine-local `NODE_EXTRA_CA_CERTS` setting. diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index 4424689847..dea51fa642 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -2174,6 +2174,10 @@ QQ 同样支持 `deepseekbot messaging-defaults qq` 和 `messaging-defaults-set ### 团队模式与 Host 成员 +使用 `team-mode owner-sign-in status` 查看目标 Host 的独立 Owner 账密登录设置。首次创建账密时执行 `team-mode owner-sign-in on --username <用户名> --password-stdin --confirm`,通过标准输入提供密码。已有账密时,执行 `team-mode owner-sign-in on --confirm` 即可继续使用。用 `off` 停止新的账密登录,已登记的 Owner 设备可以继续连接。 + +在另一端执行 `device-owner-sign-in <可信 HTTPS 地址> <用户名> --password-stdin --confirm --out <私有设备文件绝对路径>`。CLI 验证 HTTPS 地址,经已认证的设备加密通道提交密码,将设备密钥和凭据写入新建的私有文件。标准输出只报告 Host ID、设备 ID 和文件路径等连接信息。使用 `device-probe --device-file <私有设备文件绝对路径>` 验证可用该设备授权读取真实 Host Feed。 + `dm ` 在指定 Host 上打开或创建当前 Human 与该活跃联系人的唯一私聊。双方打开会返回同一频道,其他 Human 无权读取。使用 `channels send --body-stdin` 和 `channel-messages ` 收发、读取消息。纯 Human 私聊没有 Bot 参与者;群消息仍可由有权参与的 Bot 阅读。 Owner CLI 也接受私有局域网 IPv4 的 HTTPS 地址,并正常验证证书;仍拒绝局域网明文 HTTP。测试用私有 CA 可通过机器本地的 `NODE_EXTRA_CA_CERTS` 指定。 diff --git a/docs/decisions/connections.md b/docs/decisions/connections.md index fa185259d2..0b80e5958c 100644 --- a/docs/decisions/connections.md +++ b/docs/decisions/connections.md @@ -65,6 +65,22 @@ Why: on Connect, TLS ends at Cloudflare's edge, and the Human rejected Cloudflar Enforced by: `packages/core/test/connect-noise.test.ts`, `connect-encrypted-gateway.test.ts`, `connect-channel.test.ts`, `connect-secret-route.test.ts`, `device-lan.test.ts`. +### Remote Host password sign-in uses the same encrypted device channel on every route + +Accepted design for [#4896](https://github.com/BotHarness/DeepSeekBot/issues/4896). The first delivery covers standalone Owner sign-in over HTTPS in the desktop and Web Clients. [#4898](https://github.com/BotHarness/DeepSeekBot/issues/4898) + +Desktop, iOS, and Android can add a Remote Host with a Host-owned username and password. The Web Client shares the path when its existing Owner-authorized Add remote action is available. Clients verify a saved Host key or a fingerprint supplied over a trusted channel before submitting a password. For a first connection by address alone, the Human supplies a trusted HTTPS origin. The Client validates its certificate and uses that origin to establish initial trust in the Host key. + +A Host sign-in link or QR code supplies the route and fingerprint for first contact, including on an HTTP-only LAN. The Client can also use a fingerprint the Human verifies independently. A first-time HTTP address alone can discover a Host and requires proof of its identity before sign-in. A saved key mismatch ends the attempt before credential submission. Changing a route retains the Host identity and its pinned key. + +The Client and Host complete their authenticated Noise channel before exchanging credentials. Tailscale, Cloudflare Tunnel, Quick Tunnel, and other proxies can carry the channel if they forward it to the device gateway. The Host uses the same admission checks on every route. A sign-in link carries public Host discovery data and requires the Human's own credentials. The existing pairing QR continues to obtain approval on the Host. + +After authentication, the Host enrolls the exact Client device key with a revocable grant for that Human. The current Host Owner receives the same authority as an Owner-paired device. A Team member receives a member grant and completes any required first-password change before normal access. The Host records how it issued the device grant so the Host Owner can revoke password-enrolled Owner devices together when changing the password. See [Host password policy](team-mode.md#host-password-sign-in-and-team-mode). + +Why. The URL controls how a Client reaches the Host. The authenticated Host key controls which Host receives the password. This supports HTTP-only LANs and TLS-terminating relays with the same credential protection. + +Enforced by the [Remote Hosts verification journey](../../.agents/skills/verify-deepseekbot/features/remote-hosts.md#standalone-owner-password-sign-in-4898) and the remaining acceptance cases in [#4896](https://github.com/BotHarness/DeepSeekBot/issues/4896). + ## 5. Tobs Connect: an account discovers Hosts; a managed tunnel carries ciphertext diff --git a/docs/decisions/team-mode.md b/docs/decisions/team-mode.md index aa271df07f..7609d993fd 100644 --- a/docs/decisions/team-mode.md +++ b/docs/decisions/team-mode.md @@ -74,6 +74,20 @@ Why: the request remains tied to the place and Human authority that produced it. Enforced by: [team-approvals.test.ts](../../packages/core/test/team-approvals.test.ts), [bot-modes.test.ts](../../packages/core/test/bot-modes.test.ts), [team-mode.test.ts](../../packages/core/test/team-mode.test.ts), [team-minimal-members.test.ts](../../packages/core/test/team-minimal-members.test.ts), [team-member-lifecycle.test.ts](../../packages/core/test/team-member-lifecycle.test.ts). +### Host password sign-in and Team mode + +Accepted design for [#4896](https://github.com/BotHarness/DeepSeekBot/issues/4896). Standalone sign-in is the first delivery. Team mode activation and selective sign-out on password changes are tracked in separate slices. [#4898](https://github.com/BotHarness/DeepSeekBot/issues/4898) + +Team mode enables password sign-in for the current Host Owner and eligible Host Members. With Team mode off, the Host Owner can opt in to Owner-only password sign-in. The Owner sets a username and password on first setup. Existing installations reuse the current Owner's stored credentials. When Team mode is the first feature to need those credentials, the enable flow asks the Owner to create them. + +The Host stores the standalone Owner setting independently. Turning Team mode off restores its effect and revokes non-Owner grants through the existing offboarding path. Turning standalone sign-in off stops new password-based enrollment. Existing Owner device grants stay usable until revoked, and the stored credentials are available if the Owner enables sign-in again. + +Owner password changes default to revoking the other Owner device grants that password sign-in issued. The Owner can opt out. The current device and grants issued by QR pairing remain valid. The Host records issuance on the device grant and uses its existing revocation path to close affected connections. + +Why. A single Human can connect remotely with the same Host-owned credential used in Team mode. Keeping the standalone setting independent preserves the Owner's choice after Team mode ends. Recording issuance allows selective revocation after a password change. + +Enforced by the [Remote Hosts verification journey](../../.agents/skills/verify-deepseekbot/features/remote-hosts.md#standalone-owner-password-sign-in-4898) and the remaining acceptance cases in [#4896](https://github.com/BotHarness/DeepSeekBot/issues/4896). + ## 2. Each Human controls their Host-owned chat avatar diff --git a/packages/client/src/client/bot-settings-sections.tsx b/packages/client/src/client/bot-settings-sections.tsx index 658026e208..ae5797b99c 100644 --- a/packages/client/src/client/bot-settings-sections.tsx +++ b/packages/client/src/client/bot-settings-sections.tsx @@ -262,11 +262,12 @@ export function CompanionsSection({ } export function DevicesSection({ + call, t, pairPhone, joinComputer, -}: PropsLocale<'botharness'> & BotSettingsSectionOwnerProps): ReactElement { - return ; +}: SectionProps): ReactElement { + return ; } export function DataPrivacySection({ call, t }: SectionProps<{ call: BridgeCall }>): ReactElement { diff --git a/packages/client/src/client/client-settings-registration.ts b/packages/client/src/client/client-settings-registration.ts index b170d62029..daf107b4b4 100644 --- a/packages/client/src/client/client-settings-registration.ts +++ b/packages/client/src/client/client-settings-registration.ts @@ -278,7 +278,7 @@ export function registerClientSettings( order: 45, label: () => t('botSettings.section.devices'), locale: LOCALE_NS, - inject: () => ({}), + inject: () => ({ call }), }, DevicesSection, ), diff --git a/packages/client/src/client/connections-dialog.tsx b/packages/client/src/client/connections-dialog.tsx index dcfb3c7878..04e04533c0 100644 --- a/packages/client/src/client/connections-dialog.tsx +++ b/packages/client/src/client/connections-dialog.tsx @@ -1,4 +1,5 @@ import type { ReactElement } from 'react'; +import type { BridgeCall } from './bridge-transport.js'; import type { BotHarnessTranslate } from './locale.js'; import { PairedDevicesSettings } from './paired-devices.js'; @@ -34,10 +35,12 @@ export function ConnectionsDialog({ } export function ConnectionsPage({ + call, t, pairPhone = false, joinComputer = false, }: { + call: BridgeCall; t: BotHarnessTranslate; pairPhone?: boolean | undefined; joinComputer?: boolean | undefined; @@ -45,6 +48,7 @@ export function ConnectionsPage({ return ( void; selectHost: (hostId: string) => void; publish: () => void; -}): Pick { +}): Pick { const { enabled, carrier, @@ -58,6 +59,74 @@ export function createRemoteHostPairing host.routes.includes(route)) ?? + hosts.find((host) => host.hostId === hostId); + return previous; + }, + }); + if (!signed.ok) return signed; + + const host = signed.value; + let saved: SavedHost | undefined; + let cancelled = false; + try { + if ( + hostSettingsDrafts.hasDirty(host.hostId) && + !(await hostSettingsDrafts.prepare(host.hostId)) + ) { + cancelled = true; + throw new Error('request-cancelled'); + } + saved = await persistCredential(host.hostId, previous, () => { + if (input.signal?.aborted) throw new Error('request-cancelled'); + const priorRoute = readHosts(storage).find( + (item) => item.hostId !== host.hostId && item.routes.includes(input.route), + ); + if (priorRoute) throw new Error('connection-host-changed'); + return host; + }); + } catch { + await revoke(host).catch(() => undefined); + return { + ok: false, + code: cancelled || input.signal?.aborted ? 'request-cancelled' : 'storage-failed', + }; + } + if (!saved) { + await revoke(host).catch(() => undefined); + return { ok: false, code: 'storage-failed' }; + } + const existing = clients.get(saved.hostId); + if (existing) { + const releasing = releaseRemoteHostViewers(existing.client); + retireEntry(existing); + await releasing.catch(() => undefined); + } + attach(saved); + selectHost(saved.hostId); + publish(); + if (previous) await revoke(previous).catch(() => undefined); + return { ok: true, value: saved }; + }, async teamSignIn(target, localHostId, signal) { if (!enabled) return { ok: false, code: 'owner-required' }; const preparedFlow = await prepareTeamSignIn({ diff --git a/packages/client/src/client/features/team/locale.ts b/packages/client/src/client/features/team/locale.ts index b3c9679f06..0440581ae0 100644 --- a/packages/client/src/client/features/team/locale.ts +++ b/packages/client/src/client/features/team/locale.ts @@ -1,6 +1,9 @@ export const zh = { 'team.permission.models.configure': '管理默认模型、路由组和模型预设', - 'teamSignIn.useUsername': '用用户名登录', + 'ownerSignIn.title': '以 Host Owner 身份登录', + 'ownerSignIn.hint': '使用 Host Owner 提供的可信 HTTPS 地址。', + 'ownerSignIn.error.disabled': '远程 Host 的 Owner 账密登录已关闭。', + 'teamSignIn.useUsername': '以团队成员身份登录', 'teamSignIn.manualHint': '以成员身份登录别人的 Host。请向它的所有者索取 HTTPS 地址、你的用户名和一次性密码。', 'teamSignIn.address': 'Host 地址', @@ -94,7 +97,7 @@ export const zh = { 'team.invite.text.intro': '你被邀请加入 {host} 的 Team。', 'team.invite.text.phone': '手机:在 Tobs 里打开这个邀请链接(10 分钟内有效):{link}', 'team.invite.text.desktop': - '电脑:在 Tobs「环境」里点「添加远程」→「用用户名登录」,地址填 {address}', + '电脑:在 Tobs「环境」里点「添加远程」→「以团队成员身份登录」,地址填 {address}', 'team.invite.text.username': '用户名:{username}', 'team.invite.text.password': '一次性密码:{password}(第一次登录后改成你自己的密码)', 'team.invite.text.fingerprint': '登录时核对 Host 指纹:{fingerprint}', @@ -392,7 +395,10 @@ export const zh = { export const en = { 'team.permission.models.configure': 'Manage default model, Routing Groups and Model Presets', - 'teamSignIn.useUsername': 'Sign in with a username', + 'ownerSignIn.title': 'Sign in as Host Owner', + 'ownerSignIn.hint': 'Use a trusted HTTPS address from the Host Owner.', + 'ownerSignIn.error.disabled': 'Owner password sign-in is off on this Host.', + 'teamSignIn.useUsername': 'Sign in as a team member', 'teamSignIn.manualHint': "Sign in as a member of someone else's Host. Ask its owner for the HTTPS address, your username and your one-time password.", 'teamSignIn.address': 'Host address', @@ -493,7 +499,7 @@ export const en = { 'team.invite.text.phone': 'Phone: open this invitation link in Tobs (valid for 10 minutes): {link}', 'team.invite.text.desktop': - 'Computer: in Tobs Environments, choose Add remote → Sign in with a username, and enter {address}', + 'Computer: in Tobs Environments, choose Add remote → Sign in as a team member, and enter {address}', 'team.invite.text.username': 'Username: {username}', 'team.invite.text.password': 'One-time password: {password} (you choose your own password after the first sign-in)', diff --git a/packages/client/src/client/host-tabs.tsx b/packages/client/src/client/host-tabs.tsx index a266a7a521..aa03bae6d1 100644 --- a/packages/client/src/client/host-tabs.tsx +++ b/packages/client/src/client/host-tabs.tsx @@ -26,6 +26,7 @@ import { useMountedResource } from './mounted-resource.js'; import { createConnectionControl, type ConnectionAttempt } from './connection-control.js'; import { ConnectionProgress } from './connection-progress.js'; import { TeamSignInDialog, teamSignInErrorText } from './team-sign-in-dialog.js'; +import { OwnerSignInDialog } from './owner-sign-in-dialog.js'; import { parseTeamInvitation } from '@botharness/host-protocol/team-invitation'; import type { TeamSignInTarget } from '@botharness/host-client/team-sign-in'; export { useThisHost } from './this-host.js'; @@ -365,6 +366,7 @@ export function AddRemoteHostDialog({ const control = useRef>(); const attemptId = useRef(); const [team, setTeam] = useState(); + const [ownerSignIn, setOwnerSignIn] = useState(false); const [manual, setManual] = useState<{ route: string; username: string }>(); const mount = useMountedResource(() => { const sources = remoteHosts(); @@ -437,6 +439,16 @@ export function AddRemoteHostDialog({ } }; const failed = attempt?.state === 'failed' || attempt?.state === 'cancelled'; + if (ownerSignIn) + return ( + setOwnerSignIn(false)} + onClose={onClose} + t={t} + /> + ); if (team !== undefined) return (
@@ -587,6 +599,13 @@ export function AddRemoteHostDialog({ > {t(readingImage ? 'remoteHosts.add.readingImage' : 'remoteHosts.add.image')} + + ) : ( + void save({ enabled })} + /> + ) + ) : read.kind === 'failed' ? ( + + ) : undefined + } + > + {!setup && error !== undefined ? {error} : null} + + {setup ? ( + { + if (busy) return; + setError(undefined); + setSetup(false); + }} + submit={(username, password) => void save({ enabled: true, username, password })} + /> + ) : null} + + ); +} + +function SetupDialog({ + t, + busy, + error, + cancel, + submit, +}: { + t: BotHarnessTranslate; + busy: boolean; + error: string | undefined; + cancel(): void; + submit(username: string, password: string): void; +}): ReactElement { + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [confirmation, setConfirmation] = useState(''); + const validUsername = /^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username.trim()); + const passwordTooLong = new TextEncoder().encode(password).length > 1024; + const validPassword = password.length >= TEAM_PASSWORD_MIN_LENGTH && !passwordTooLong; + return ( + submit(username.trim(), password)} + > + + + 0 && confirmation !== password + ? t('team.password.mismatch') + : undefined + } + onChange={setConfirmation} + /> + + ); +} diff --git a/packages/client/src/client/owner-sign-in-dialog.tsx b/packages/client/src/client/owner-sign-in-dialog.tsx new file mode 100644 index 0000000000..78dbb6e1e6 --- /dev/null +++ b/packages/client/src/client/owner-sign-in-dialog.tsx @@ -0,0 +1,135 @@ +import { useRef, useState, type ReactElement } from 'react'; + +import { TextField } from './ds/field.js'; +import { FormDialog } from './ds/form-dialog.js'; +import type { BotHarnessTranslate } from './locale.js'; +import { useMountedResource } from './mounted-resource.js'; +import { remoteHosts, type RemoteOwnerSignInError } from './remote-hosts.js'; +import { teamSignInErrorText } from './team-sign-in-dialog.js'; +import { getThisHost } from './this-host.js'; + +function httpsOrigin(input: string): string | undefined { + try { + const url = new URL(input.includes('://') ? input : 'https://' + input); + if ( + url.protocol === 'https:' && + !url.username && + !url.password && + !url.hash && + !url.search && + url.pathname === '/' + ) + return url.origin; + } catch {} +} + +function signInError( + t: BotHarnessTranslate, + code: RemoteOwnerSignInError, + retryAfterSeconds?: number, +): string { + if (code === 'owner-sign-in-disabled') return t('ownerSignIn.error.disabled'); + if (code === 'already-paired') return t('remoteHosts.error.already-paired'); + return teamSignInErrorText(t, code, retryAfterSeconds); +} + +export function OwnerSignInDialog({ + inline, + footerContainer, + onBack, + onClose, + t, +}: { + inline: boolean; + footerContainer?: HTMLElement | null | undefined; + onBack: () => void; + onClose: () => void; + t: BotHarnessTranslate; +}): ReactElement { + const [address, setAddress] = useState(''); + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [error, setError] = useState(); + const [busy, setBusy] = useState(false); + const pending = useRef(); + const mount = useMountedResource(() => () => pending.current?.abort(), []); + const submit = () => { + if (pending.current) return; + const route = httpsOrigin(address.trim()); + if (!route) { + setError(t('teamSignIn.error.insecure-transport')); + return; + } + const controller = new AbortController(); + pending.current = controller; + setError(undefined); + setBusy(true); + const host = getThisHost(); + void remoteHosts() + .ownerSignIn({ + route, + username: username.trim(), + password, + deviceName: t('remoteHosts.deviceName', { name: host.name ?? 'Host' }).slice(0, 60), + ...(host.id === undefined ? {} : { localHostId: host.id }), + signal: controller.signal, + }) + .then((result) => { + if (controller.signal.aborted) return; + if (result.ok) { + setPassword(''); + onClose(); + } else { + if (result.code === 'credentials-invalid') setPassword(''); + setError(signInError(t, result.code, result.retryAfterSeconds)); + } + }) + .catch(() => { + if (!controller.signal.aborted) setError(t('teamSignIn.error.generic')); + }) + .finally(() => { + if (pending.current === controller) pending.current = undefined; + if (!controller.signal.aborted) setBusy(false); + }); + }; + return ( + + + ); +} diff --git a/packages/client/src/client/paired-devices.tsx b/packages/client/src/client/paired-devices.tsx index 5ed4e8b08e..1438f6c861 100644 --- a/packages/client/src/client/paired-devices.tsx +++ b/packages/client/src/client/paired-devices.tsx @@ -40,6 +40,8 @@ import { } from './paired-device-setup.js'; import { renderPairedDeviceNetworkStatus } from './paired-device-network-status.js'; import { json, PATH, usePairedDevices } from './use-paired-devices.js'; +import { OwnerPasswordSignInSettings } from './owner-password-sign-in-settings.js'; +import type { BridgeCall } from './bridge-transport.js'; export type { ConnectedHost }; @@ -173,6 +175,7 @@ export type PairedDevicesSettingsProps = PropsLocale<'botharness'> & { page?: boolean; initialPairing?: boolean; initialRemote?: boolean; + ownerPasswordSignInCall?: BridgeCall; pairedDeviceId?: string | undefined; onDevicePaired?: ((deviceId: string) => void) | undefined; onFeedRead?: ((deviceId: string) => void) | undefined; @@ -186,6 +189,7 @@ export function PairedDevicesSettings({ page = false, initialPairing = false, initialRemote = false, + ownerPasswordSignInCall, onDevicePaired, onFeedRead, pairedDeviceId, @@ -490,6 +494,9 @@ export function PairedDevicesSettings({ ) : null} {standalone && section === 'devices' && overview ? ( + {ownerPasswordSignInCall === undefined ? null : ( + + )} {snapshot?.lan ? ( ; + export interface RemoteHosts { + ownerSignIn( + input: RemoteOwnerSignInInput, + ): Promise>; teamSignIn( target: TeamSignInTarget, localHostId?: string, @@ -557,7 +567,7 @@ export function createRemoteHosts(options: { refreshCredentials(); }; - const { teamSignIn, pair } = createRemoteHostPairing({ + const { ownerSignIn, teamSignIn, pair } = createRemoteHostPairing({ enabled, carrier, storage, @@ -825,6 +835,7 @@ export function createRemoteHosts(options: { notifications.stop(); }; }, + ownerSignIn, teamSignIn, pair, async forgetLocal(hostId) { diff --git a/packages/client/test/owner-password-sign-in-settings.test.tsx b/packages/client/test/owner-password-sign-in-settings.test.tsx new file mode 100644 index 0000000000..38d07e965d --- /dev/null +++ b/packages/client/test/owner-password-sign-in-settings.test.tsx @@ -0,0 +1,151 @@ +// @vitest-environment jsdom +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { Simulate } from 'react-dom/test-utils'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import type { BridgeCall } from '../src/client/bridge.js'; +import { ConnectionsPage } from '../src/client/connections-dialog.js'; +import { zhTranslate } from '../src/client/locale.js'; + +vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({ + ...(await import('./primitive-mocks.js')).shellPrimitives(), +})); + +let host: HTMLDivElement; +let root: ReturnType; + +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => + Response.json({ + host: { id: 'test-host', name: 'Studio' }, + devices: [], + routes: { routes: [], tailscale: 'missing' }, + relationships: [], + }), + ), + ); + host = document.createElement('div'); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +function button(label: string, within: ParentNode = host): HTMLButtonElement { + const match = [...within.querySelectorAll('button')].find((node) => node.textContent === label); + if (!match) throw new Error(`Missing button: ${label}`); + return match; +} + +function field(inputLabel: string): HTMLInputElement { + const label = [...document.querySelectorAll('label')].find( + (node) => node.textContent === inputLabel, + ); + const input = label?.control; + if (!(input instanceof HTMLInputElement)) throw new Error(`Missing input: ${inputLabel}`); + return input; +} + +async function fill(label: string, value: string): Promise { + await act(async () => { + const input = field(label); + input.value = value; + Simulate.change(input); + }); +} + +function signInSwitch(): HTMLButtonElement { + const toggle = host.querySelector('[role="switch"][aria-label="账密登录"]'); + if (!toggle) throw new Error('Missing sign-in switch'); + return toggle; +} + +it('sets up sign-in, then toggles it without re-entering credentials', async () => { + let configured = false; + let enabled = false; + const call = vi.fn(async (method, args) => { + if (method === 'ownerPasswordSignInSet') { + configured = true; + enabled = args['enabled'] === true; + } + return { + ok: true, + value: configured ? { enabled, username: 'studio-owner' } : { enabled }, + }; + }); + await act(async () => root.render()); + await act(async () => button('设置账密').click()); + await fill(zhTranslate('team.members.username'), 'studio-owner'); + await fill(zhTranslate('team.password.new'), 'some-test-password'); + const dialog = document.querySelector('[role="dialog"]'); + if (!dialog) throw new Error('Missing sign-in setup dialog'); + expect(button(zhTranslate('team.ownerPassword.saveAndEnable'), dialog).disabled).toBe(true); + await fill(zhTranslate('team.password.confirm'), 'some-test-password'); + await act(async () => button(zhTranslate('team.ownerPassword.saveAndEnable'), dialog).click()); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + expect(host.textContent).toContain('studio-owner'); + const toggle = signInSwitch(); + expect(toggle.getAttribute('aria-checked')).toBe('true'); + await act(async () => toggle.click()); + expect(toggle.getAttribute('aria-checked')).toBe('false'); + await act(async () => toggle.click()); + expect(toggle.getAttribute('aria-checked')).toBe('true'); + expect( + call.mock.calls + .filter(([method]) => method === 'ownerPasswordSignInSet') + .map(([, args]) => args), + ).toEqual([ + { enabled: true, username: 'studio-owner', password: 'some-test-password' }, + { enabled: false }, + { enabled: true }, + ]); +}); + +it('preserves the last settings value if a toggle is refused', async () => { + let refuse = true; + const call = vi.fn(async (method) => { + if (method === 'ownerPasswordSignInSet' && refuse) { + return { ok: false, error: { code: 'unavailable', message: 'unavailable', details: {} } }; + } + return { + ok: true, + value: { enabled: method === 'ownerPasswordSignInSet', username: 'existing-owner' }, + }; + }); + await act(async () => root.render()); + await act(async () => signInSwitch().click()); + expect(signInSwitch().getAttribute('aria-checked')).toBe('false'); + expect(host.textContent).toContain('保存失败,再试一次。'); + refuse = false; + await act(async () => signInSwitch().click()); + expect(signInSwitch().getAttribute('aria-checked')).toBe('true'); + expect(host.textContent).not.toContain('保存失败,再试一次。'); +}); + +it('keeps the Owner controls unavailable in a member shell', async () => { + vi.stubGlobal('__DSH_REMOTE_ACCESS__', { owner: false }); + const call = vi.fn(async () => ({ + ok: true, + value: { enabled: true, username: 'studio-owner' }, + })); + await act(async () => root.render()); + expect(host.textContent).not.toContain('账密登录'); + expect(call).not.toHaveBeenCalled(); +}); + +it('hides the controls when the Host refuses the Owner permission', async () => { + const call = vi.fn(async () => ({ + ok: false, + error: { code: 'permission-required', message: 'permission-required', details: {} }, + })); + await act(async () => root.render()); + expect(host.textContent).not.toContain('账密登录'); + expect(call).toHaveBeenCalledExactlyOnceWith('ownerPasswordSignIn', {}, expect.any(AbortSignal)); +}); diff --git a/packages/client/test/owner-sign-in-dialog.test.tsx b/packages/client/test/owner-sign-in-dialog.test.tsx new file mode 100644 index 0000000000..b6dd82c923 --- /dev/null +++ b/packages/client/test/owner-sign-in-dialog.test.tsx @@ -0,0 +1,63 @@ +// @vitest-environment jsdom +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { expect, it, vi } from 'vitest'; + +vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({ + ...(await import('./primitive-mocks.js')).shellPrimitives(), +})); +const ownerSignIn = vi.hoisted(() => vi.fn()); +vi.mock('../src/client/remote-hosts.js', () => ({ remoteHosts: () => ({ ownerSignIn }) })); +vi.mock('../src/client/this-host.js', () => ({ + getThisHost: () => ({ id: 'local', name: 'Desk' }), +})); + +import { OwnerSignInDialog } from '../src/client/owner-sign-in-dialog.js'; +import { zhTranslate } from '../src/client/locale.js'; + +function fill(input: HTMLInputElement | null, value: string) { + if (!input) throw new Error('Missing input'); + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(input, value); + input.dispatchEvent(new Event('input', { bubbles: true })); +} + +it('signs in from one form, gives one invalid-credentials error, and clears the failed password', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + ownerSignIn.mockResolvedValueOnce({ ok: false, code: 'credentials-invalid' }); + ownerSignIn.mockResolvedValueOnce({ ok: true, value: { hostId: 'studio' } }); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + const onClose = vi.fn(); + try { + await act(async () => + root.render(), + ); + const password = container.querySelector('input[type="password"]'); + const submit = container.querySelector('button[type="submit"]'); + await act(async () => { + fill(container.querySelector('input[autocomplete="url"]'), 'studio.example'); + fill(container.querySelector('input[autocomplete="username"]'), 'alice'); + fill(password, 'wrong-password'); + }); + await act(async () => submit?.click()); + expect(container.querySelector('[role="alert"]')?.textContent).toBe( + zhTranslate('teamSignIn.error.credentials-invalid'), + ); + expect(ownerSignIn).toHaveBeenCalledWith( + expect.objectContaining({ + route: 'https://studio.example', + username: 'alice', + password: 'wrong-password', + localHostId: 'local', + }), + ); + expect(password?.value).toBe(''); + await act(async () => fill(password, 'new-password')); + await act(async () => submit?.click()); + expect(onClose).toHaveBeenCalledOnce(); + } finally { + await act(async () => root.unmount()); + container.remove(); + } +}); diff --git a/packages/core/src/bots/cli-device-client.ts b/packages/core/src/bots/cli-device-client.ts index f4f1b81b19..178f21f895 100644 --- a/packages/core/src/bots/cli-device-client.ts +++ b/packages/core/src/bots/cli-device-client.ts @@ -2,7 +2,8 @@ import { createHash, randomBytes } from 'node:crypto'; import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { isAbsolute } from 'node:path'; import { createConnectAccount } from '@botharness/host-client/connect-account'; -import { pairHost } from '@botharness/host-client/pairing'; +import { pairHost, revokePairing } from '@botharness/host-client/pairing'; +import { signInOwnerDevice } from '@botharness/host-client/owner-sign-in'; import { parseSavedHost, serializeSavedHost } from '@botharness/host-client/hosts'; import { createHostClient } from '@botharness/host-client/client'; import { isLanRoute, isEncryptedRoute } from '@botharness/host-protocol/route'; @@ -21,6 +22,11 @@ export const DEVICE_CLIENT_COMMANDS = [ description: 'pair from a trusted --link-file --confirm; write keys only to a new private --out file', }, + { + command: 'device-owner-sign-in', + description: + 'sign in to a trusted as with --password-stdin --confirm; save keys to a new private --out file', + }, { command: 'device-probe', description: @@ -38,11 +44,67 @@ export async function runDeviceClientCommand( 'host-id'?: string; out?: string; confirm?: boolean; + 'password-stdin'?: boolean; }, writeStatus: (line: string) => void = (line) => { process.stderr.write(line); }, + readStdin?: () => Promise, ): Promise { + if (command === 'device-owner-sign-in') { + const [route, username] = rest; + if ( + rest.length !== 2 || + !route || + !username || + !values['password-stdin'] || + !readStdin || + !values.out || + !isAbsolute(values.out) + ) + throw new CliLiveError( + 'usage', + 'Provide a trusted HTTPS origin, username, --password-stdin and a new absolute --out file.', + ); + if (!values.confirm) + throw new CliLiveError( + 'confirm-required', + 'Confirm the HTTPS address came from the trusted Host Owner with --confirm.', + ); + if (existsSync(values.out)) throw new CliLiveError('output-exists', 'Choose a new --out file.'); + const password = (await readStdin()).replace(/\r?\n$/u, ''); + if (!password) throw new CliLiveError('invalid-input', 'Provide the password on stdin.'); + const carrier = nodeDeviceCarrier(); + const result = await signInOwnerDevice({ + carrier, + route, + username, + password, + deviceName: 'CLI device', + }); + if (!result.ok) throw new CliLiveError(result.code, 'Owner device sign-in refused.'); + const host = result.value; + try { + writeFileSync(values.out, `${JSON.stringify(serializeSavedHost(host))}\n`, { + flag: 'wx', + mode: 0o600, + }); + } catch { + const retired = await revokePairing({ host, carrier }); + throw new CliLiveError( + retired === 'revoked' ? 'storage-failed' : 'device-revocation-unconfirmed', + retired === 'revoked' + ? 'Cannot save the device file. The new device was revoked.' + : 'Cannot save the device file. Check the new CLI device in the Host device list.', + ); + } + return { + hostId: host.hostId, + deviceId: host.deviceId, + encrypted: true, + pairing: { path: values.out }, + }; + } if (rest.length) throw new CliLiveError('usage', `${command} takes no positional arguments.`); if (command === 'device-pair' || command === 'device-account-pair') { const accountPair = command === 'device-account-pair'; diff --git a/packages/core/src/bots/cli-effects.ts b/packages/core/src/bots/cli-effects.ts index 7f0d34adfb..6d313fe0f6 100644 --- a/packages/core/src/bots/cli-effects.ts +++ b/packages/core/src/bots/cli-effects.ts @@ -223,6 +223,7 @@ export const CLI_EFFECTS = { 'device-offer': { effects: management, brokerRead: false }, 'device-offer-status': { effects: read, brokerRead: true }, 'device-pair': { effects: externalSecretManagement, brokerRead: false }, + 'device-owner-sign-in': { effects: externalSecretManagement, brokerRead: false }, 'device-probe': { effects: write, brokerRead: false }, 'device-requests': { effects: read, brokerRead: true }, 'device-revoke': { effects: management, brokerRead: false }, @@ -640,6 +641,10 @@ function familyEffects( ? destructiveManagement : management; case 'team-mode': + if (action === 'owner-sign-in') { + if (rest[1] === 'status') return read; + return values['password-stdin'] ? secretManagement : management; + } return action === 'status' ? read : action === 'owner-password' || action === 'transfer-owner' diff --git a/packages/core/src/bots/cli-live-dispatch.ts b/packages/core/src/bots/cli-live-dispatch.ts index 6834ee575d..40ccf85751 100644 --- a/packages/core/src/bots/cli-live-dispatch.ts +++ b/packages/core/src/bots/cli-live-dispatch.ts @@ -238,7 +238,7 @@ export async function runLiveCli( ); } if (DEVICE_CLIENT_COMMANDS.some((entry) => entry.command === command)) - return runDeviceClientCommand(command, rest, values); + return runDeviceClientCommand(command, rest, values, undefined, io.readStdin); if (command === 'cloud-work') { const input = await prepareCloudWork(rest, values, io); const host = await connectLiveHost(values, io, AbortSignal.timeout(timeoutMs(values.timeout))); diff --git a/packages/core/src/bots/cli-team.ts b/packages/core/src/bots/cli-team.ts index 244405a158..df39942fab 100644 --- a/packages/core/src/bots/cli-team.ts +++ b/packages/core/src/bots/cli-team.ts @@ -45,7 +45,7 @@ export const TEAM_COMMANDS = [ { command: 'team-mode', description: - 'status | on | off | owner-password --password-stdin | insecure-http on|off --confirm | transfer-owner --password-stdin --confirm', + 'status | on | off | owner-password --password-stdin | owner-sign-in status|on|off | insecure-http on|off --confirm | transfer-owner --password-stdin --confirm', }, { command: 'members', @@ -357,6 +357,21 @@ export async function runTeamCommand( : rpc('memberDeviceRevoke', { humanId, grantId: values.revoke }); } if (command === 'team-mode') { + if (action === 'owner-sign-in' && rest.length === 2) { + const username = values.username; + const readPassword = values['password-stdin'] === true; + if (argument === 'status' && username === undefined && !readPassword && !values.confirm) + return rpc('ownerPasswordSignIn', {}); + if (argument === 'off' && username === undefined && !readPassword) + return rpc('ownerPasswordSignInSet', { enabled: false }); + if (argument !== 'on' || (username !== undefined) !== readPassword) return usage(); + if (!values.confirm) + throw new CliLiveError('confirm-required', 'Enabling Owner sign-in requires --confirm.'); + return rpc('ownerPasswordSignInSet', { + enabled: true, + ...(username === undefined ? {} : { username, password: await secret(io) }), + }); + } if ( action === 'transfer-owner' && argument && diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index 0bc0008ef4..f2b0f34cc8 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -491,6 +491,12 @@ export class BotharnessBridgeService extends TypertRemoteService { teamModeSet(enabled: boolean) { return teamRpc.teamModeSet(this.methods, enabled); } + ownerPasswordSignIn() { + return teamRpc.ownerPasswordSignIn(this.methods); + } + ownerPasswordSignInSet(enabled: boolean, username?: string, password?: string) { + return teamRpc.ownerPasswordSignInSet(this.methods, enabled, username, password); + } teamOwnerPasswordSet(password: string, current?: string) { return teamRpc.teamOwnerPasswordSet(this.methods, password, current); } @@ -3439,6 +3445,8 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'modelsAllowed', 'usageByMember', 'teamModeSet', + 'ownerPasswordSignIn', + 'ownerPasswordSignInSet', 'teamOwnerPasswordSet', 'teamInsecureHttpSet', 'members', diff --git a/packages/core/src/database/schema-plan.ts b/packages/core/src/database/schema-plan.ts index 56b5acc78e..0c45059120 100644 --- a/packages/core/src/database/schema-plan.ts +++ b/packages/core/src/database/schema-plan.ts @@ -4075,6 +4075,20 @@ const ROLE_ENGINE_ACCOUNTS_MIGRATION: SchemaMigration = { }, }; +const OWNER_PASSWORD_SIGN_IN_MIGRATION: SchemaMigration = { + id: 'owner-password-sign-in', + module: 'team', + description: 'Standalone Owner password sign-in policy and paired-device enrollment provenance', + migrate(database) { + database.exec(` + ALTER TABLE team_settings ADD COLUMN owner_password_sign_in INTEGER NOT NULL DEFAULT 0 + CHECK (owner_password_sign_in IN (0, 1)); + ALTER TABLE paired_devices ADD COLUMN enrollment TEXT + CHECK (enrollment = 'owner-password'); + `); + }, +}; + export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ SESSION_OWNERSHIP_MIGRATION, MESSAGING_TRACER_MIGRATION, @@ -4252,4 +4266,5 @@ export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ ROLE_MODEL_PROVIDERS_MIGRATION, SESSION_TURN_TARGET_MIGRATION, ROLE_ENGINE_ACCOUNTS_MIGRATION, + OWNER_PASSWORD_SIGN_IN_MIGRATION, ]); diff --git a/packages/core/src/devices/encrypted-gateway.ts b/packages/core/src/devices/encrypted-gateway.ts index 6739e8457a..f51b14aba2 100644 --- a/packages/core/src/devices/encrypted-gateway.ts +++ b/packages/core/src/devices/encrypted-gateway.ts @@ -24,6 +24,7 @@ import { } from '../voice/call-contract.js'; import { DIRECT_PATH, type DirectResult } from './direct.js'; import { APP_VERSION_HEADER } from './client-compat.js'; +import { noisePeerHeaders } from './route-context.js'; const BODY_LIMIT = 4 * 1024 * 1024; const QUEUE_LIMIT = 20 * 1024 * 1024; @@ -154,6 +155,8 @@ export function createEncryptedGateway(options: { deviceId: string | undefined, closed = false, admitted = false; + let channelHeaders: Record = {}; + let ownerSignInAttempted = false; let enrollmentOffer: { body: string; offer: string } | undefined; let detach: (() => void) | undefined; const streams = new Map(); @@ -595,6 +598,7 @@ export function createEncryptedGateway(options: { method, headers: { authorization: `Device ${credential!}`, + ...channelHeaders, ...appVersionHeader(input), 'content-type': input['contentType'] === 'application/octet-stream' @@ -642,18 +646,21 @@ export function createEncryptedGateway(options: { const type = input['type']; if (!admitted) { const publicKey = Buffer.from(channel.peerKey()).toString('hex'); - if (type === 'team-sign-in' && options.memberDevices) { + if ((type === 'team-sign-in' || type === 'owner-sign-in') && options.memberDevices) { + const ownerSignIn = type === 'owner-sign-in'; + const reply = ownerSignIn ? 'owner-signed-in' : 'team-signed-in'; + if (ownerSignIn && ownerSignInAttempted) return refuse('invalid-input'); + if (ownerSignIn) ownerSignInAttempted = true; try { - const result = await options.memberDevices.signIn( - input['input'], - remoteAddress, - publicKey, - ); - if (!closed) send({ type: 'team-signed-in', result: { ok: true, value: result } }); + const result = ownerSignIn + ? await options.memberDevices.signInOwner(input['input'], remoteAddress, publicKey) + : await options.memberDevices.signIn(input['input'], remoteAddress, publicKey); + if (!closed) send({ type: reply, result: { ok: true, value: result } }); + else if (ownerSignIn) options.pairing.revoke(result.deviceId); } catch (error) { if (!closed) send({ - type: 'team-signed-in', + type: reply, result: { ok: false, code: error instanceof TeamError ? error.code : 'invalid-input', @@ -740,6 +747,8 @@ export function createEncryptedGateway(options: { publicKey, ); if (!admission.ok) return refuse(admission.code); + if (admission.device.enrollment === 'owner-password') + channelHeaders = noisePeerHeaders(publicKey); admitted = true; negotiating--; encrypted++; @@ -769,7 +778,7 @@ export function createEncryptedGateway(options: { const stream = new WebSocket( `ws://127.0.0.1:${options.port()}/botharness-device/api/remote.mux`, { - headers: { authorization: `Device ${credential!}` }, + headers: { authorization: `Device ${credential!}`, ...channelHeaders }, maxPayload: BODY_LIMIT, perMessageDeflate: false, handshakeTimeout: DEADLINE, diff --git a/packages/core/src/devices/gateway.ts b/packages/core/src/devices/gateway.ts index 2488b25ac1..11eb5c1a1f 100644 --- a/packages/core/src/devices/gateway.ts +++ b/packages/core/src/devices/gateway.ts @@ -11,7 +11,13 @@ import { LOCAL_VIDEO_PATH, type LocalVideoResult, } from '../../../computer/src/local-video-contract.js'; -import { DEVICE_ROUTE_HEADER, forwardDeviceRoute, isConnectRequest } from './route-context.js'; +import { + DEVICE_NOISE_PEER_HEADER, + DEVICE_ROUTE_HEADER, + forwardDeviceRoute, + isConnectRequest, + noisePeerKey, +} from './route-context.js'; import { VOICE_CALL_CONNECT_REFUSAL, VOICE_CALL_LIMITS, @@ -63,6 +69,7 @@ const NEVER_FORWARDED = new Set([ 'sec-fetch-dest', 'sec-fetch-user', DEVICE_ROUTE_HEADER, + DEVICE_NOISE_PEER_HEADER, ]); const WEBSOCKET_HEADERS = [ 'upgrade', @@ -188,6 +195,8 @@ async function readSmall(request: IncomingMessage, limit: number): Promise + pairing.admit(header(request, 'authorization'), noisePeerKey(request)); const now = options.now ?? Date.now; const log = options.log ?? (() => {}); const loopback = (): string => `127.0.0.1:${String(options.port())}`; @@ -223,7 +232,7 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa const streamTicket = (request: IncomingMessage, response: ServerResponse): void => { if (request.method !== 'POST') return refuse(response, 404, 'not-found'); - const admission = pairing.admit(header(request, 'authorization')); + const admission = admit(request); if (!admission.ok) return refuse(response, 401, admission.code); for (const [key, ticket] of streamTickets) if (ticket.expiresAt <= now()) streamTickets.delete(key); @@ -299,7 +308,7 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa const unpair = (request: IncomingMessage, response: ServerResponse): void => { if (request.method !== 'POST') return refuse(response, 404, 'not-found'); - const admission = pairing.admit(header(request, 'authorization')); + const admission = admit(request); if (!admission.ok) return refuse(response, 401, admission.code); pairing.revoke(admission.device.id); response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }); @@ -308,7 +317,7 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa const remove = async (request: IncomingMessage, response: ServerResponse): Promise => { if (request.method !== 'POST') return refuse(response, 404, 'not-found'); - const admission = pairing.admit(header(request, 'authorization')); + const admission = admit(request); if (!admission.ok) return refuse(response, 401, admission.code); let input: { deviceId?: unknown } = {}; try { @@ -351,7 +360,7 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa path: string, handler = options.push!, ): Promise => { - const admission = pairing.admit(header(request, 'authorization')); + const admission = admit(request); if (!admission.ok) return refuse(response, 401, admission.code); let body: Record = {}; if (request.method === 'POST') { @@ -690,7 +699,7 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa } if (path === DEVICE_FEED_READ_PATH) { if (request.method !== 'POST') return refuse(response, 404, 'not-found'); - const admission = pairing.admit(header(request, 'authorization')); + const admission = admit(request); if (!admission.ok) return refuse(response, 401, admission.code); const receipt = pairing.acknowledgeFeed(admission.device.id); if (!receipt.ok) return refuse(response, 401, receipt.code); @@ -719,16 +728,11 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa return devicePush(request, response, path); if (decodedPath === `${DEVICE_GATEWAY_PREFIX}${LOCAL_VIDEO_PATH}`) - return video(request, response, pairing.admit(header(request, 'authorization'))); + return video(request, response, admit(request)); if (decodedPath === `${DEVICE_GATEWAY_PREFIX}${VOICE_CALL_PATH}`) - return call(request, response, pairing.admit(header(request, 'authorization'))); + return call(request, response, admit(request)); if (path.startsWith(`${DEVICE_GATEWAY_PREFIX}/api/`)) - return forward( - request, - response, - pairing.admit(header(request, 'authorization')), - DEVICE_GATEWAY_PREFIX, - ); + return forward(request, response, admit(request), DEVICE_GATEWAY_PREFIX); return refuse(response, 404, 'not-found'); }, @@ -746,7 +750,7 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa const ticketed = pathname === DEVICE_MUX_PATH ? ticketAdmission(request) : undefined; if (crossOrigin(request) && (ticketed === undefined || hostOrigin(request) === undefined)) return refuseUpgrade(socket, 403, 'origin-refused'); - const admission = ticketed ?? pairing.admit(header(request, 'authorization')); + const admission = ticketed ?? admit(request); if (!admission.ok) return refuseUpgrade(socket, 401, admission.code); const target = pathname === DEVICE_MUX_PATH diff --git a/packages/core/src/devices/pairing.ts b/packages/core/src/devices/pairing.ts index 8239997d01..a4e095aab0 100644 --- a/packages/core/src/devices/pairing.ts +++ b/packages/core/src/devices/pairing.ts @@ -17,6 +17,7 @@ export interface HostIdentity { export interface PairedDevice { id: string; name: string; + enrollment?: 'owner-password'; humanId?: string; publicKey?: string; pairedAt: string; @@ -73,6 +74,7 @@ export type Admission = { ok: true; device: PairedDevice } | { ok: false; code: export type DevicePairingEvent = | { phase: 'offer-created' | 'offer-expired' | 'offer-refused' } | { phase: 'offer-redeemed' | 'device-admitted'; deviceId: string } + | { phase: 'owner-password-enrolled'; deviceId: string } | { phase: 'device-refused'; code: DeviceRefusal; deviceId?: string } | { phase: 'device-revoked'; deviceId: string; closedStreams: number }; @@ -103,6 +105,11 @@ export interface DevicePairing { verifier?: string; publicKey?: string; }): Redemption; + issueOwnerPasswordDevice(input: { + humanId: string; + name: string; + publicKey: string; + }): { deviceId: string; credential: string } | undefined; requestKey(input: { offer: string; publicKey: string; @@ -113,7 +120,7 @@ export interface DevicePairing { approveKey(receipt: string, publicKey: string): boolean; cancelRelationshipOffers(relationshipId: string, publicKey: string): number; admitKey(authorization: string | undefined, publicKey: string): Admission; - admit(authorization: string | undefined): Admission; + admit(authorization: string | undefined, noisePublicKey?: string): Admission; check(deviceId: string): Admission; acknowledgeFeed(deviceId: string): Admission; list(): PairedDevice[]; @@ -156,6 +163,7 @@ interface Row { name: string; secret_hash: string; public_key: string | null; + enrollment?: 'owner-password' | null; paired_at: string; last_seen_at: string | null; feed_read_at: string | null; @@ -172,6 +180,7 @@ function device(row: Row): PairedDevice { id: row.device_id, name: row.name, pairedAt: row.paired_at, + ...(row.enrollment === 'owner-password' ? { enrollment: row.enrollment } : {}), ...(row.public_key === null ? {} : { publicKey: row.public_key }), ...(row.last_seen_at === null ? {} : { lastSeenAt: row.last_seen_at }), ...(row.feed_read_at == null ? {} : { feedReadAt: row.feed_read_at }), @@ -467,16 +476,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin }, admitKey(authorization, publicKey) { - if (authorization?.startsWith('Device member.')) { - const member = options.members?.admit(authorization, publicKey); - return member - ? { ok: true, device: member } - : { ok: false, code: options.members?.refusal(authorization) ?? 'device-unknown' }; - } - const admitted = this.admit(authorization); - if (!admitted.ok) return admitted; - if (admitted.device.publicKey !== publicKey) return { ok: false, code: 'device-unknown' }; - return admitted; + return this.admit(authorization, publicKey); }, redeem(input) { @@ -603,9 +603,39 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin }; }, - admit(authorization) { + issueOwnerPasswordDevice(input) { + if (input.humanId !== ownerHumanId() || !/^[a-f0-9]{64}$/u.test(input.publicKey)) + return undefined; + const id = token(16); + const secret = token(32); + const pairedAt = iso(now()); + const name = deviceName(input.name); + database.transaction( + (connection) => + connection + .prepare( + `INSERT INTO paired_devices + (device_id, name, secret_hash, paired_at, public_key, human_id, enrollment) + VALUES (?, ?, ?, ?, ?, ?, 'owner-password')`, + ) + .run( + id, + name, + digest(secret).toString('hex'), + pairedAt, + input.publicKey, + input.humanId, + ), + ['paired-devices'], + ); + record({ phase: 'owner-password-enrolled', deviceId: id }); + options.onPaired?.({ id, name, pairedAt, enrollment: 'owner-password' }); + return { deviceId: id, credential: `${id}.${secret}` }; + }, + + admit(authorization, noisePublicKey) { if (authorization?.startsWith('Device member.')) { - const member = options.members?.admit(authorization); + const member = options.members?.admit(authorization, noisePublicKey); return member ? { ok: true, device: member } : { ok: false, code: options.members?.refusal(authorization) ?? 'device-unknown' }; @@ -620,7 +650,9 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin const presented = digest(match[2]!); if ( current === undefined || - !timingSafeEqual(presented, Buffer.from(current.secret_hash, 'hex')) + !timingSafeEqual(presented, Buffer.from(current.secret_hash, 'hex')) || + ((noisePublicKey !== undefined || current.enrollment === 'owner-password') && + (noisePublicKey === undefined || current.public_key !== noisePublicKey)) ) { record({ phase: 'device-refused', code: 'device-unknown' }); return { ok: false, code: 'device-unknown' }; diff --git a/packages/core/src/devices/route-context.ts b/packages/core/src/devices/route-context.ts index f7bab68e46..eab70afde4 100644 --- a/packages/core/src/devices/route-context.ts +++ b/packages/core/src/devices/route-context.ts @@ -2,8 +2,24 @@ import { randomBytes } from 'node:crypto'; import type { IncomingMessage } from 'node:http'; export const DEVICE_ROUTE_HEADER = 'x-botharness-device-route'; +export const DEVICE_NOISE_PEER_HEADER = 'x-botharness-device-noise-peer'; const connectTag = randomBytes(32).toString('base64url'); const managedTlsTag = randomBytes(32).toString('base64url'); +const noisePeerTag = randomBytes(32).toString('base64url'); + +export function noisePeerHeaders(publicKey: string): Record { + return { [DEVICE_NOISE_PEER_HEADER]: `${noisePeerTag}.${publicKey}` }; +} + +export function noisePeerKey(request: IncomingMessage): string | undefined { + if (!['127.0.0.1', '::ffff:127.0.0.1', '::1'].includes(request.socket.remoteAddress ?? '')) + return; + const header = request.headers[DEVICE_NOISE_PEER_HEADER]; + if (typeof header !== 'string') return; + const [tag, publicKey, extra] = header.split('.'); + if (tag === noisePeerTag && extra === undefined && publicKey && /^[a-f0-9]{64}$/u.test(publicKey)) + return publicKey; +} export function stampConnectRoute(request: IncomingMessage): void { stampRoute(request, connectTag); diff --git a/packages/core/src/features/team/rpc.ts b/packages/core/src/features/team/rpc.ts index ed1c81714a..a58662bfab 100644 --- a/packages/core/src/features/team/rpc.ts +++ b/packages/core/src/features/team/rpc.ts @@ -124,6 +124,19 @@ export function teamModeSet(methods: TeamBridgeMethods, enabled: boolean) { return unwrapAsync(methods.teamModeSet({ enabled })); } +export function ownerPasswordSignIn(methods: TeamBridgeMethods) { + return unwrapAsync(methods.ownerPasswordSignIn({})); +} + +export function ownerPasswordSignInSet( + methods: TeamBridgeMethods, + enabled: boolean, + username?: string, + password?: string, +) { + return unwrapAsync(methods.ownerPasswordSignInSet({ enabled, username, password })); +} + export function teamOwnerPasswordSet( methods: TeamBridgeMethods, password: string, diff --git a/packages/core/src/team/bridge.ts b/packages/core/src/team/bridge.ts index a7d26c20a0..67920cf045 100644 --- a/packages/core/src/team/bridge.ts +++ b/packages/core/src/team/bridge.ts @@ -148,6 +148,22 @@ export function createTeamBridge(human: HumanContext, team: TeamService | undefi call((service) => service.setMode(human, z.object({ enabled: z.boolean() }).parse(payload).enabled), ), + ownerPasswordSignIn: (_payload: unknown) => + call((service) => service.ownerPasswordSignIn(human)), + ownerPasswordSignInSet: (payload: unknown) => + call((service) => + service.ownerPasswordSignInSet( + human, + z + .object({ + enabled: z.boolean(), + username: z.string().max(32).optional(), + password: z.string().max(1024).optional(), + }) + .strict() + .parse(payload), + ), + ), teamOwnerPasswordSet: (payload: unknown) => call((service) => { const { password, current } = z diff --git a/packages/core/src/team/devices.ts b/packages/core/src/team/devices.ts index 9262454d0b..261c6e88b4 100644 --- a/packages/core/src/team/devices.ts +++ b/packages/core/src/team/devices.ts @@ -82,6 +82,20 @@ export function createMemberDevices(options: { }); return { ...options.team.deviceGrantResult(signed, signed.member), host: identity }; }, + async signInOwner(input: unknown, ip: string, publicKey: string) { + const parsed = deviceSignInSchema.parse(input); + const identity = await host(); + if (parsed.fingerprint !== identity.fingerprint) throw new TeamError('fingerprint-mismatch'); + return options.team.signInOwnerDevice(parsed.username, parsed.password, ip, (humanId) => { + const issued = options.pairing.issueOwnerPasswordDevice({ + humanId, + name: parsed.deviceName, + publicKey, + }); + if (!issued) throw new TeamError('credentials-invalid'); + return { ...issued, host: identity }; + }); + }, }; } export type MemberDevices = ReturnType; diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts index 008c8d2c25..f67cb46316 100644 --- a/packages/core/src/team/service.ts +++ b/packages/core/src/team/service.ts @@ -93,6 +93,7 @@ function credentialPasswordJson( return JSON.stringify(ownerIssuerHumanId === undefined ? hash : { ...hash, ownerIssuerHumanId }); } const credentialSchema = z.object({ + username: z.string(), password_json: z.string(), history_json: z.string(), must_change: z.coerce.boolean(), @@ -426,7 +427,7 @@ export class TeamService { const row = this.db.read((db) => db .prepare( - 'SELECT password_json, history_json, must_change FROM member_credentials WHERE human_id = ?', + 'SELECT username, password_json, history_json, must_change FROM member_credentials WHERE human_id = ?', ) .get(humanId), ); @@ -434,6 +435,7 @@ export class TeamService { const parsed = credentialSchema.parse(row); const password = credentialPasswordSchema.parse(JSON.parse(parsed.password_json)); return { + username: parsed.username, hash: passwordHashSchema.parse(password), ownerIssuerHumanId: password.ownerIssuerHumanId, history: z.array(passwordHashSchema).parse(JSON.parse(parsed.history_json)), @@ -494,6 +496,91 @@ export class TeamService { throw new TeamError('permission-required', undefined, { permission: 'owner' }); } + private ownerPasswordEnabled(): boolean { + return this.db.read( + (db) => + db.prepare('SELECT owner_password_sign_in FROM team_settings WHERE singleton = 1').get() + ?.owner_password_sign_in === 1, + ); + } + + ownerPasswordSignIn(human: HumanContext): { enabled: boolean; username?: string } { + this.owner(human); + const username = this.credential(human.humanId)?.username; + return { + enabled: this.ownerPasswordEnabled(), + ...(username === undefined ? {} : { username }), + }; + } + + async ownerPasswordSignInSet( + human: HumanContext, + input: { enabled: boolean; username?: string | undefined; password?: string | undefined }, + ): Promise<{ enabled: boolean; username?: string }> { + const previous = this.ownerPasswordSignIn(human); + const { enabled, username, password } = input; + if (enabled && previous.username === undefined) { + if (username === undefined || password === undefined) + throw new TeamError('owner-password-required'); + if (!/^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username)) throw new TeamError('username-invalid'); + if (!strongPassword(password)) throw new TeamError('password-weak'); + if (this.byUsername(username)) throw new TeamError('username-taken'); + const hash = await hashPassword(password); + this.owner(human); + if (this.hasCredential(human.humanId)) throw new TeamError('invalid-input'); + if (this.byUsername(username)) throw new TeamError('username-taken'); + this.db.transaction( + (db) => { + db.prepare('INSERT INTO member_credentials VALUES (?, ?, ?, ?, 0)').run( + human.humanId, + username, + credentialPasswordJson(hash, human.humanId), + '[]', + ); + db.prepare( + 'UPDATE team_settings SET owner_password_sign_in = 1 WHERE singleton = 1', + ).run(); + }, + ['team'], + ); + } else { + if (username !== undefined || password !== undefined) throw new TeamError('invalid-input'); + if (previous.enabled === enabled) return previous; + this.db.transaction( + (db) => + db + .prepare('UPDATE team_settings SET owner_password_sign_in = ? WHERE singleton = 1') + .run(Number(enabled)), + ['team'], + ); + } + this.invalidate(); + this.log('owner-password-sign-in-changed', { initiator: 'owner', enabled }); + return this.ownerPasswordSignIn(human); + } + + async signInOwnerDevice( + username: string, + password: string, + ip: string, + issue: (humanId: string) => T, + ): Promise { + if (!this.ownerPasswordEnabled()) throw new TeamError('owner-sign-in-disabled'); + this.passwordAttempt(username, ip); + const { humanId } = this.ownerContext(); + const credential = this.credential(humanId); + const matches = credential?.username === username; + const valid = await verifyPassword(password, matches ? credential.hash : DUMMY_PASSWORD_HASH); + if (!matches || !valid) throw new TeamError('credentials-invalid'); + if (!this.ownerPasswordEnabled()) throw new TeamError('owner-sign-in-disabled'); + if ( + this.ownerContext().humanId !== humanId || + this.credential(humanId)?.hash.hash !== credential.hash.hash + ) + throw new TeamError('credentials-invalid'); + return issue(humanId); + } + async setMode(human: HumanContext, enabled: boolean): Promise { this.roles.require(human, 'team.settings'); if (enabled && !this.hasCredential(this.ownerContext().humanId)) diff --git a/packages/core/test/cli-device-client.test.ts b/packages/core/test/cli-device-client.test.ts index cb2fa507f9..55b4e52546 100644 --- a/packages/core/test/cli-device-client.test.ts +++ b/packages/core/test/cli-device-client.test.ts @@ -3,12 +3,48 @@ import { join } from 'node:path'; import { expect, it, vi } from 'vitest'; import { createTempRoot } from './helpers.js'; const paired = vi.hoisted(() => vi.fn()); -vi.mock('@botharness/host-client/pairing', () => ({ pairHost: paired })); +const ownerSignIn = vi.hoisted(() => vi.fn()); +vi.mock('@botharness/host-client/pairing', () => ({ pairHost: paired, revokePairing: vi.fn() })); +vi.mock('@botharness/host-client/owner-sign-in', () => ({ signInOwnerDevice: ownerSignIn })); vi.mock('../src/devices/connect-identity-fetch.js', () => ({ requestConnectIdentity: (url: string, init?: RequestInit) => fetch(url, init), })); import { runDeviceClientCommand } from '../src/bots/cli-device-client.js'; +it('writes Owner sign-in credentials to a private file and emits only connection metadata', async () => { + const out = join(createTempRoot('owner-sign-in-cli-'), 'device.json'); + const args = ['https://studio.example.test', 'alice']; + const values = { 'password-stdin': true, out }; + const password = 'private-owner-password'; + const readStdin = vi.fn(async () => password + '\n'); + await expect( + runDeviceClientCommand('device-owner-sign-in', args, values, undefined, readStdin), + ).rejects.toMatchObject({ code: 'confirm-required' }); + expect(readStdin).not.toHaveBeenCalled(); + + ownerSignIn.mockResolvedValueOnce({ + ok: true, + value: { hostId: 'studio', deviceId: 'device', credential: 'private-grant', routes: [args[0]] }, + }); + const result = await runDeviceClientCommand( + 'device-owner-sign-in', + args, + { ...values, confirm: true }, + undefined, + readStdin, + ); + expect(ownerSignIn).toHaveBeenCalledWith( + expect.objectContaining({ route: args[0], username: 'alice', password }), + ); + expect(result).toEqual({ + hostId: 'studio', + deviceId: 'device', + encrypted: true, + pairing: { path: out }, + }); + expect(JSON.parse(readFileSync(out, 'utf8'))).toMatchObject({ credential: 'private-grant' }); +}); + it('requires trusted-file confirmation and never returns saved device secrets on stdout', async () => { const root = createTempRoot('lan-cli-'); const link = join(root, 'link.txt'), diff --git a/packages/core/test/cli-team.test.ts b/packages/core/test/cli-team.test.ts index e212f16fb6..13c2d0db5a 100644 --- a/packages/core/test/cli-team.test.ts +++ b/packages/core/test/cli-team.test.ts @@ -416,6 +416,7 @@ describe('Team CLI', () => { 'device-notifications', 'phone-notifications', 'device-pair', + 'device-owner-sign-in', 'device-probe', ])('refuses --as before %s device dispatch', async (command) => { const f = await host(); @@ -436,6 +437,13 @@ describe('Team CLI', () => { [['team-mode', 'status'], 'teamMode', {}], [['team-mode', 'on'], 'teamModeSet', { enabled: true }], [['team-mode', 'off'], 'teamModeSet', { enabled: false }], + [['team-mode', 'owner-sign-in', 'status'], 'ownerPasswordSignIn', {}], + [ + ['team-mode', 'owner-sign-in', 'on', '--confirm'], + 'ownerPasswordSignInSet', + { enabled: true }, + ], + [['team-mode', 'owner-sign-in', 'off'], 'ownerPasswordSignInSet', { enabled: false }], [['team-mode', 'insecure-http', 'on', '--confirm'], 'teamInsecureHttpSet', { allowed: true }], [['members', 'list'], 'members', {}], [['roles', 'list'], 'roles', {}], @@ -470,6 +478,25 @@ describe('Team CLI', () => { ]); }); + it('creates standalone Owner credentials from stdin without echoing the password', async () => { + const f = await host(); + const args = ['team-mode', 'owner-sign-in', 'on', '--username', 'alice', '--password-stdin']; + const password = 'private-owner-sign-in-password'; + const unconfirmed = await run(f.url, args, password); + expect(unconfirmed.status).not.toBe(0); + expect(f.calls).toHaveLength(0); + + const result = await run(f.url, [...args, '--confirm'], password + '\n'); + expect(result.status).toBe(0); + expect(result.text + result.errorText).not.toContain(password); + expect(f.calls).toMatchObject([ + { + path: '/api/botharness/ownerPasswordSignInSet', + input: { payload: { args: { enabled: true, username: 'alice', password } } }, + }, + ]); + }); + it('resolves an invitation username and prints only the bridge link JSON', async () => { const f = await host(); const result = await run(f.url, ['members', 'invite', 'bob']); diff --git a/packages/core/test/owner-password-device-sign-in.test.ts b/packages/core/test/owner-password-device-sign-in.test.ts new file mode 100644 index 0000000000..88a1cc722f --- /dev/null +++ b/packages/core/test/owner-password-device-sign-in.test.ts @@ -0,0 +1,182 @@ +import { randomBytes } from 'node:crypto'; +import { encryptedCarrier, openNoiseSocket } from '@botharness/host-client/encrypted-carrier'; +import { afterEach, expect, it } from 'vitest'; +import { z } from 'zod'; +import { OWNER_HUMAN_CONTEXT as owner, humanContext } from '../src/humans/context.js'; +import { cleanup, memberDeviceHost, teamFixture } from './team-mode-fixtures.js'; + +afterEach(cleanup); + +const target = 'https://habcdefghijkl.deepseekbot.dev'; +const password = 'standalone-owner-password-1'; +const deviceEncryption = (f: ReturnType) => ({ + protocol: f.encryption.protocol, + hostKey: f.encryption.publicKey, + deviceKey: randomBytes(32).toString('hex'), +}); + +async function signIn( + f: ReturnType, + host: Awaited>, + encryption: ReturnType, + { + username = 'my-owner', + attempt = password, + fingerprint = f.encryption.fingerprint, + repeat = false, + } = {}, +) { + return new Promise((resolve, reject) => { + let result: unknown; + const socket = openNoiseSocket({ + origin: target, + hostId: f.pairing.host().id, + encryption, + raw: host.carrier, + message(frame) { + if (repeat && frame['type'] === 'refused' && frame['code'] === 'invalid-input') { + resolve(result); + socket.close(); + return; + } + if (frame['type'] !== 'owner-signed-in') return; + result = frame['result']; + if (!repeat) { + resolve(result); + socket.close(); + } + }, + closed: (reason) => reject(new Error(reason)), + }); + void socket.ready.then(() => { + const request = { + type: 'owner-sign-in', + input: { username, password: attempt, deviceName: 'Desktop', fingerprint }, + }; + socket.send(request); + if (repeat) socket.send(request); + }, reject); + }); +} + +it('enrolls an Owner device through Noise with Team mode off and revokes its admitted connection', async () => { + const f = teamFixture(); + const host = await memberDeviceHost(f); + const bridge = f.methods(owner); + const encryption = deviceEncryption(f); + expect(await bridge.ownerPasswordSignIn({})).toEqual({ ok: true, value: { enabled: false } }); + expect(await signIn(f, host, encryption)).toEqual({ ok: false, code: 'owner-sign-in-disabled' }); + expect( + await bridge.ownerPasswordSignInSet({ enabled: true, username: 'my-owner', password }), + ).toEqual({ ok: true, value: { enabled: true, username: 'my-owner' } }); + expect(f.team.enabled()).toBe(false); + + const result = z + .object({ + ok: z.literal(true), + value: z.object({ + host: z.object({ id: z.string(), name: z.string(), fingerprint: z.string() }), + deviceId: z.string(), + credential: z.string(), + }), + }) + .parse(await signIn(f, host, encryption, { repeat: true })); + const { credential, deviceId } = result.value; + expect(result.value.host).toEqual({ ...f.pairing.host(), fingerprint: f.encryption.fingerprint }); + expect(credential.startsWith(deviceId + '.')).toBe(true); + expect(f.pairing.list()).toMatchObject([{ id: deviceId, enrollment: 'owner-password' }]); + expect((await host.post('/feed-read', {}, credential)).status).toBe(401); + expect(f.pairing.admitKey(`Device ${credential}`, 'c'.repeat(64))).toEqual({ + ok: false, + code: 'device-unknown', + }); + + const carrier = encryptedCarrier({ + credential, + encryption, + hostId: result.value.host.id, + raw: host.carrier, + }); + const acknowledge = () => + carrier.request(target + '/botharness-device/feed-read', { + method: 'POST', + signal: AbortSignal.timeout(5_000), + }); + try { + expect((await acknowledge()).status).toBe(200); + expect(await bridge.ownerPasswordSignInSet({ enabled: false })).toEqual({ + ok: true, + value: { enabled: false, username: 'my-owner' }, + }); + expect((await acknowledge()).status).toBe(200); + expect(await signIn(f, host, deviceEncryption(f))).toEqual({ + ok: false, + code: 'owner-sign-in-disabled', + }); + expect(f.pairing.revoke(deviceId)).toMatchObject({ revoked: true, closedStreams: 1 }); + await expect(acknowledge()).rejects.toThrow(); + } finally { + carrier.close?.(); + } +}); + +it('reuses an existing Owner credential and keeps standalone configuration Owner-only', async () => { + const f = teamFixture(); + await f.team.setOwnerPassword(owner, password); + await f.team.setMode(owner, true); + const member = await f.team.createMember(owner, 'member', 'Member'); + const memberContext = humanContext(member.member.humanId); + await f.team.changePassword(memberContext, member.initialPassword, 'member-password-1'); + const other = f.methods(memberContext); + expect(await other.ownerPasswordSignIn({})).toMatchObject({ + ok: false, + error: { code: 'permission-required' }, + }); + expect(await other.ownerPasswordSignInSet({ enabled: true })).toMatchObject({ + ok: false, + error: { code: 'permission-required' }, + }); + await f.team.setMode(owner, false); + expect(await f.methods(owner).ownerPasswordSignInSet({ enabled: true })).toEqual({ + ok: true, + value: { enabled: true, username: 'owner' }, + }); + const host = await memberDeviceHost(f); + expect(await signIn(f, host, deviceEncryption(f), { username: 'owner' })).toMatchObject({ + ok: true, + }); +}); + +it('uses the same failure and account/source limits for missing and wrong Owner credentials', async () => { + const f = teamFixture(); + await f.methods(owner).ownerPasswordSignInSet({ enabled: true, username: 'my-owner', password }); + const targetHost = await memberDeviceHost(f); + const wrong = { ok: false, code: 'credentials-invalid' }; + expect(await signIn(f, targetHost, deviceEncryption(f), { fingerprint: 'different' })).toEqual({ + ok: false, + code: 'fingerprint-mismatch', + }); + for (const username of ['my-owner', 'no-such-user']) { + for (let attempt = 0; attempt < 5; attempt++) + expect( + await signIn(f, targetHost, deviceEncryption(f), { username, attempt: 'wrong' }), + ).toEqual(wrong); + expect( + await signIn(f, targetHost, deviceEncryption(f), { username, attempt: 'wrong' }), + ).toEqual({ + ok: false, + code: 'rate-limited', + retryAfterSeconds: 60, + }); + } + for (let index = 0; index < 10; index++) + expect( + await signIn(f, targetHost, deviceEncryption(f), { username: `unlisted-${index}` }), + ).toEqual(wrong); + expect(await signIn(f, targetHost, deviceEncryption(f), { username: 'another-user' })).toEqual({ + ok: false, + code: 'rate-limited', + retryAfterSeconds: 60, + }); + expect(f.pairing.list()).toEqual([]); +}, 30_000); diff --git a/packages/host-client/src/client.ts b/packages/host-client/src/client.ts index c5ad74683d..45b41799bf 100644 --- a/packages/host-client/src/client.ts +++ b/packages/host-client/src/client.ts @@ -3,6 +3,7 @@ import { checkRoute, isConnectRoute, isEncryptedRoute, + isHttpsOrigin, isLanRoute, socketOrigin, } from '@botharness/host-protocol/route'; @@ -955,7 +956,8 @@ export function createHostClient(options: HostClientOptions): HostClient { }, resource: resources.resource, secretInputAllowed: () => - checkRoute(route, options.encryption?.privateRelay).ok && + (checkRoute(route, options.encryption?.privateRelay).ok || + (options.encryption?.required === true && isHttpsOrigin(route))) && (!isEncryptedRoute(route, options.encryption) || options.encryption !== undefined), onLive(listener) { liveListeners.add(listener); diff --git a/packages/host-client/src/encrypted-carrier.ts b/packages/host-client/src/encrypted-carrier.ts index 8f6ccf639b..6285b8b448 100644 --- a/packages/host-client/src/encrypted-carrier.ts +++ b/packages/host-client/src/encrypted-carrier.ts @@ -13,6 +13,7 @@ import { hasPrivateOrigin, isConnectRoute, isEncryptedRoute, + isHttpsOrigin, isLanRoute, socketOrigin, } from '@botharness/host-protocol/route'; @@ -31,7 +32,7 @@ export class ConnectRefused extends Error { function requestUrl( input: string, - privateOrigin?: Parameters[1], + encryption?: HostEncryption, trustedHttpsOrigins: readonly string[] = [], ): URL { let url: URL; @@ -41,8 +42,9 @@ function requestUrl( throw new ConnectRefused('route-invalid'); } if ( - (!checkRoute(url.origin, privateOrigin).ok && - !(url.protocol === 'https:' && trustedHttpsOrigins.includes(url.origin))) || + (!checkRoute(url.origin, encryption?.privateRelay).ok && + !(url.protocol === 'https:' && trustedHttpsOrigins.includes(url.origin)) && + !(encryption?.required && isHttpsOrigin(url.origin))) || url.username || url.password || url.hash @@ -125,6 +127,7 @@ export function openNoiseSocket(options: { }) { if ( !checkRoute(options.origin, options.encryption.privateRelay).ok && + !(options.encryption.required && isHttpsOrigin(options.origin)) && !( options.trustedHttpsOrigins?.includes(options.origin) && new URL(options.origin).protocol === 'https:' && @@ -302,13 +305,14 @@ export function encryptedCarrier(options: { if (options.raw.custody && isCustodyHandle(options.credential)) return options.raw.custody({ hostId: options.hostId, credential: options.credential }); const needsEncryption = (origin: string) => - isEncryptedRoute(origin, options.encryption) && - !( - options.trustedHttpsOrigins?.includes(origin) && - !isConnectRoute(origin) && - !isLanRoute(origin) && - !options.encryption?.privateRelay - ); + options.encryption?.required === true || + (isEncryptedRoute(origin, options.encryption) && + !( + options.trustedHttpsOrigins?.includes(origin) && + !isConnectRoute(origin) && + !isLanRoute(origin) && + !options.encryption?.privateRelay + )); const sessions = new Map(); const directs = new Map(); const retries = new Map(); @@ -511,7 +515,7 @@ export function encryptedCarrier(options: { url: string, init: HostRequest, ): Promise => { - const parsed = requestUrl(url, options.encryption?.privateRelay, options.trustedHttpsOrigins); + const parsed = requestUrl(url, options.encryption, options.trustedHttpsOrigins); await waitForAdmission(current.ready, init.signal); if (init.signal.aborted) throw new Error('request-cancelled'); if ( @@ -586,7 +590,7 @@ export function encryptedCarrier(options: { directs.clear(); }, async request(url, init) { - const parsed = requestUrl(url, options.encryption?.privateRelay, options.trustedHttpsOrigins); + const parsed = requestUrl(url, options.encryption, options.trustedHttpsOrigins); if (!options.requireEncryption && !needsEncryption(parsed.origin)) return options.raw.request(url, init); if (init.signal.aborted) throw new Error('request-cancelled'); @@ -595,7 +599,7 @@ export function encryptedCarrier(options: { openSocket(url, events, headers): HostSocket { const parsed = requestUrl( url.replace(/^ws/u, 'http'), - options.encryption?.privateRelay, + options.encryption, options.trustedHttpsOrigins, ); if (!options.requireEncryption && !needsEncryption(parsed.origin)) diff --git a/packages/host-client/src/encrypted-sign-in.ts b/packages/host-client/src/encrypted-sign-in.ts new file mode 100644 index 0000000000..38ea8651d5 --- /dev/null +++ b/packages/host-client/src/encrypted-sign-in.ts @@ -0,0 +1,94 @@ +import type { HostCarrier } from '@botharness/host-protocol/carrier'; +import { + teamRecord, + type TeamHostIdentity, + type TeamResult, +} from '@botharness/host-protocol/team-invitation'; +import type { HostEncryption } from './hosts'; +import { ConnectRefused, HOST_KEY_REJECTIONS, openNoiseSocket } from './encrypted-carrier'; + +type TransportRefusal = 'request-cancelled' | 'fingerprint-mismatch' | 'unreachable'; + +export function signInTransportFailure( + error: unknown, + signal: AbortSignal, +): TeamResult { + if (signal.aborted) return { ok: false, code: 'request-cancelled' }; + if (error instanceof ConnectRefused && HOST_KEY_REJECTIONS.has(error.code)) + return { ok: false, code: 'fingerprint-mismatch' }; + return { ok: false, code: 'unreachable' }; +} + +export function signInRefusal( + reply: unknown, + codes: readonly E[], +): TeamResult { + const { code, retryAfterSeconds } = teamRecord(reply); + return { + ok: false, + code: codes.find((known) => known === code) ?? 'response-invalid', + ...(typeof retryAfterSeconds === 'number' && + Number.isFinite(retryAfterSeconds) && + retryAfterSeconds > 0 + ? { retryAfterSeconds } + : {}), + }; +} + +export function encryptedSignIn(options: { + type: 'owner-sign-in' | 'team-sign-in'; + carrier: HostCarrier; + route: string; + host: TeamHostIdentity; + encryption: HostEncryption; + input: unknown; + signal: AbortSignal; + codes: readonly E[]; +}): Promise> { + return new Promise((resolve) => { + let done = false; + let socket: ReturnType | undefined; + const finish = (result: TeamResult) => { + if (done) return; + done = true; + clearTimeout(timer); + options.signal.removeEventListener('abort', abort); + resolve(result); + socket?.close(); + }; + const abort = () => finish({ ok: false, code: 'request-cancelled' }); + const timer = setTimeout(() => finish({ ok: false, code: 'unreachable' }), 30_000); + options.signal.addEventListener('abort', abort, { once: true }); + if (options.signal.aborted) { + abort(); + return; + } + const replyType = options.type === 'owner-sign-in' ? 'owner-signed-in' : 'team-signed-in'; + try { + socket = openNoiseSocket({ + origin: options.route, + hostId: options.host.id, + encryption: options.encryption, + raw: options.carrier, + closed: (reason) => + finish(signInTransportFailure(new ConnectRefused(reason), options.signal)), + message: (frame) => { + if (frame['type'] !== replyType) return; + const result = teamRecord(frame['result']); + finish( + result['ok'] === true + ? { ok: true, value: result['value'] } + : signInRefusal(result, options.codes), + ); + }, + }); + void socket.ready + .then(() => { + if (!done) socket?.send({ type: options.type, input: options.input }); + }) + .catch((error: unknown) => finish(signInTransportFailure(error, options.signal))); + } catch (error) { + finish(signInTransportFailure(error, options.signal)); + } + }); +} diff --git a/packages/host-client/src/hosts.ts b/packages/host-client/src/hosts.ts index ced8988e23..4e42fb4643 100644 --- a/packages/host-client/src/hosts.ts +++ b/packages/host-client/src/hosts.ts @@ -94,7 +94,8 @@ export function parseSavedHost(input: unknown): SavedHost | undefined { ) return undefined; if ( - record(value['encryption'])['loopback'] === 'encrypted' && + (record(value['encryption'])['loopback'] === 'encrypted' || + record(value['encryption'])['required'] === true) && parseEncryption(value['encryption']) === undefined ) return undefined; @@ -239,6 +240,7 @@ export function parseEncryption(input: unknown): HostEncryption | undefined { protocol: 'connect-noise-xk-v1', hostKey: value['hostKey'], deviceKey: value['deviceKey'], + ...(value['required'] === true ? { required: value['required'] } : {}), ...(value['loopback'] === 'encrypted' ? { loopback: 'encrypted' as const } : {}), } : undefined; diff --git a/packages/host-client/src/owner-sign-in.ts b/packages/host-client/src/owner-sign-in.ts new file mode 100644 index 0000000000..d4722b73d9 --- /dev/null +++ b/packages/host-client/src/owner-sign-in.ts @@ -0,0 +1,134 @@ +import type { HostCarrier } from '@botharness/host-protocol/carrier'; +import { CONNECT_CHANNEL_PATH } from '@botharness/host-protocol/noise/channel'; +import { noiseFingerprint } from '@botharness/host-protocol/noise/xk'; +import { isHttpsOrigin } from '@botharness/host-protocol/route'; +import { + teamHostIdentity, + teamRecord, + type TeamResult, +} from '@botharness/host-protocol/team-invitation'; +import { keyBytes, keyHex, secureRandom } from './encrypted-carrier'; +import { encryptedSignIn, signInTransportFailure } from './encrypted-sign-in'; +import type { HostEncryption, SavedHost } from './hosts'; + +const refusals = [ + 'credentials-invalid', + 'rate-limited', + 'owner-sign-in-disabled', + 'insecure-transport', + 'fingerprint-mismatch', + 'invalid-input', + 'remote-access/denied', +] as const; + +export type OwnerSignInError = + | (typeof refusals)[number] + | 'already-paired' + | 'this-host' + | 'response-invalid' + | 'unreachable' + | 'request-cancelled'; + +export interface OwnerSignInOptions { + carrier: HostCarrier; + route: string; + username: string; + password: string; + deviceName: string; + localHostId?: string; + previous?: (hostId: string, route: string) => SavedHost | undefined; + allowExisting?: (host: SavedHost) => boolean; + signal?: AbortSignal; +} + +export async function signInOwnerDevice( + options: OwnerSignInOptions, +): Promise> { + const { carrier, route, username, password, deviceName } = options; + if (!isHttpsOrigin(route)) return { ok: false, code: 'insecure-transport' }; + if ( + !username || + username.length > 32 || + !password || + password.length > 1024 || + !deviceName.trim() || + deviceName.length > 60 + ) + return { ok: false, code: 'invalid-input' }; + const signal = AbortSignal.any([ + AbortSignal.timeout(30_000), + ...(options.signal ? [options.signal] : []), + ]); + if (signal.aborted) return { ok: false, code: 'request-cancelled' }; + try { + const response = await carrier.request(route + CONNECT_CHANNEL_PATH, { + method: 'GET', + redirect: 'error', + signal, + }); + if (response.status !== 200) return { ok: false, code: 'unreachable' }; + const discovery = teamRecord(JSON.parse(await response.text())); + const advertised = teamRecord(discovery['encryption']); + const host = teamHostIdentity({ + ...teamRecord(discovery['host']), + fingerprint: advertised['fingerprint'], + }); + const publicKey = advertised['publicKey']; + if (!host || typeof publicKey !== 'string' || !/^[a-f0-9]{64}$/u.test(publicKey)) + return { ok: false, code: 'response-invalid' }; + if (host.id === options.localHostId) return { ok: false, code: 'this-host' }; + if (noiseFingerprint(keyBytes(publicKey)) !== host.fingerprint) + return { ok: false, code: 'fingerprint-mismatch' }; + const previous = options.previous?.(host.id, route); + if ( + previous && + (previous.hostId !== host.id || + (previous.encryption && previous.encryption.hostKey !== publicKey) || + (previous.member && previous.member.fingerprint !== host.fingerprint)) + ) + return { ok: false, code: 'fingerprint-mismatch' }; + if (previous && options.allowExisting?.(previous) === false) + return { ok: false, code: 'already-paired' }; + const encryption: HostEncryption = { + protocol: 'connect-noise-xk-v1', + required: true, + hostKey: publicKey, + deviceKey: keyHex(secureRandom(carrier)), + }; + const result = await encryptedSignIn({ + type: 'owner-sign-in', + carrier, + route, + host, + encryption, + signal, + input: { username, password, deviceName, fingerprint: host.fingerprint }, + codes: refusals, + }); + if (!result.ok) return result; + const { host: reply, deviceId, credential } = teamRecord(result.value); + const signedHost = teamHostIdentity(reply); + if (signedHost?.id !== host.id || signedHost.fingerprint !== host.fingerprint) + return { ok: false, code: 'fingerprint-mismatch' }; + if ( + typeof deviceId !== 'string' || + typeof credential !== 'string' || + !/^[A-Za-z0-9_-]{16,64}\.[A-Za-z0-9_-]{32,128}$/u.test(credential) || + !credential.startsWith(deviceId + '.') + ) + return { ok: false, code: 'response-invalid' }; + return { + ok: true, + value: { + hostId: host.id, + hostName: signedHost.name, + routes: [route], + deviceId, + credential, + encryption, + }, + }; + } catch (error) { + return signInTransportFailure(error, signal); + } +} diff --git a/packages/host-client/src/team-client.ts b/packages/host-client/src/team-client.ts index a479f307dc..b42b0ebb09 100644 --- a/packages/host-client/src/team-client.ts +++ b/packages/host-client/src/team-client.ts @@ -1,13 +1,7 @@ import type { HostCarrier } from '@botharness/host-protocol/carrier'; import type { HostEncryption, SavedHost } from './hosts'; -import { - ConnectRefused, - encryptedCarrier, - keyBytes, - keyHex, - openNoiseSocket, - secureRandom, -} from './encrypted-carrier'; +import { encryptedCarrier, keyBytes, keyHex, secureRandom } from './encrypted-carrier'; +import { encryptedSignIn, signInRefusal, signInTransportFailure } from './encrypted-sign-in'; import { isConnectRoute } from '@botharness/host-protocol/route'; import { noiseFingerprint } from '@botharness/host-protocol/noise/xk'; import { @@ -29,7 +23,7 @@ export type { } from '@botharness/host-protocol/team-invitation'; export { memberPasswordGate, prepareMemberIdentity } from './member-identity'; -const codes: ReadonlySet = new Set([ +const codes: readonly TeamErrorCode[] = [ 'credentials-invalid', 'rate-limited', 'insecure-transport', @@ -41,31 +35,7 @@ const codes: ReadonlySet = new Set([ 'password-reused', 'invalid-input', 'remote-access/denied', -]); -function refusal(value: unknown): TeamResult { - const input = teamRecord(value); - const code = input['code']; - const known = - typeof code === 'string' && codes.has(code) ? (code as TeamErrorCode) : 'response-invalid'; - return { - ok: false, - code: known, - ...(typeof input['retryAfterSeconds'] === 'number' && - Number.isFinite(input['retryAfterSeconds']) && - input['retryAfterSeconds'] > 0 - ? { retryAfterSeconds: input['retryAfterSeconds'] } - : {}), - }; -} -function requestFailure(error: unknown, signal: AbortSignal): TeamResult { - if (signal.aborted) return { ok: false, code: 'request-cancelled' }; - if ( - error instanceof ConnectRefused && - ['channel-authentication-failed', 'channel-handshake-rejected'].includes(error.code) - ) - return { ok: false, code: 'fingerprint-mismatch' }; - return { ok: false, code: 'unreachable' }; -} +]; function signedHost( input: unknown, invitation: TeamInvitation, @@ -105,57 +75,6 @@ function signedHost( }, }; } -async function encryptedSignIn(options: { - carrier: HostCarrier; - route: string; - host: TeamHostIdentity; - encryption: HostEncryption; - input: unknown; - signal: AbortSignal; -}): Promise> { - return new Promise((resolve) => { - let done = false; - let socket: ReturnType | undefined; - const finish = (result: TeamResult) => { - if (done) return; - done = true; - clearTimeout(timer); - options.signal.removeEventListener('abort', abort); - resolve(result); - socket?.close(); - }; - const abort = () => finish({ ok: false, code: 'request-cancelled' }); - const timer = setTimeout(() => finish({ ok: false, code: 'unreachable' }), 30_000); - options.signal.addEventListener('abort', abort, { once: true }); - if (options.signal.aborted) { - abort(); - return; - } - try { - socket = openNoiseSocket({ - origin: options.route, - hostId: options.host.id, - encryption: options.encryption, - raw: options.carrier, - closed: (reason) => finish(requestFailure(new ConnectRefused(reason), options.signal)), - message: (frame) => { - if (frame['type'] !== 'team-signed-in') return; - const result = teamRecord(frame['result']); - finish(result['ok'] === true ? { ok: true, value: result['value'] } : refusal(result)); - }, - }); - void socket.ready.then( - () => { - if (!done) socket?.send({ type: 'team-sign-in', input: options.input }); - }, - (error) => finish(requestFailure(error, options.signal)), - ); - } catch (error) { - finish(requestFailure(error, options.signal)); - } - }); -} - export function signInAgainInvitation( host: SavedHost, now = Date.now(), @@ -245,6 +164,8 @@ async function signInTeamRoute( if (isConnectRoute(route)) { const result = await encryptedSignIn({ ...options, + type: 'team-sign-in', + codes, route, host: invitation.host, encryption, @@ -262,9 +183,9 @@ async function signInTeamRoute( const value: unknown = JSON.parse(await result.text()); return result.status === 200 ? signedHost(value, invitation, route, encryption) - : refusal(value); + : signInRefusal(value, codes); } catch (error) { - return requestFailure(error, signal); + return signInTransportFailure(error, signal); } } function encodeInvitation(value: TeamInvitation): string { @@ -304,13 +225,13 @@ export async function changeTeamDevicePassword(options: { body: JSON.stringify({ current: options.current, next: options.next }), signal, }); - if (response.status !== 200) return refusal(JSON.parse(await response.text())); + if (response.status !== 200) return signInRefusal(JSON.parse(await response.text()), codes); return { ok: true, value: { ...options.host, member: { ...options.host.member, mustChangePassword: false } }, }; } catch (error) { - return requestFailure(error, signal); + return signInTransportFailure(error, signal); } finally { carrier.close?.(); } @@ -345,6 +266,6 @@ export async function memberPairingOffer(client: { }, }; } catch (error) { - return refusal(error); + return signInRefusal(error, codes); } } diff --git a/packages/host-client/test/owner-sign-in.test.ts b/packages/host-client/test/owner-sign-in.test.ts new file mode 100644 index 0000000000..695dab5e53 --- /dev/null +++ b/packages/host-client/test/owner-sign-in.test.ts @@ -0,0 +1,193 @@ +import { randomBytes } from 'node:crypto'; +import { describe, expect, it, vi } from 'vitest'; +import type { HostCarrier, HostRequest, HostSocketEvents } from '@botharness/host-protocol/carrier'; +import { ConnectChannel } from '@botharness/host-protocol/noise/channel'; +import { noiseFingerprint, noisePublicKey } from '@botharness/host-protocol/noise/xk'; +import { teamRecord } from '@botharness/host-protocol/team-invitation'; +import { encryptedCarrier } from '../src/encrypted-carrier'; +import { parseSavedHost, serializeSavedHost } from '../src/hosts'; +import { signInOwnerDevice } from '../src/owner-sign-in'; + +const route = 'https://studio.example'; +const password = 'test-only-sign-in-password'; +const deviceId = 'test-device-1234'; +const credential = deviceId + '.' + 'a'.repeat(43); + +function host({ differentSocketKey = false } = {}) { + const privateKey = randomBytes(32); + const publicKey = noisePublicKey(privateKey); + const identity = { id: 'studio', name: 'Studio', fingerprint: noiseFingerprint(publicKey) }; + const encryption = { + publicKey: Buffer.from(publicKey).toString('hex'), + fingerprint: identity.fingerprint, + }; + const request = vi.fn(async (_url: string, _init: HostRequest) => ({ + status: 200, + text: async () => JSON.stringify({ host: identity, encryption }), + })); + const messages: unknown[] = []; + const wire: string[] = []; + const openSocket = vi.fn((_url: string, events: HostSocketEvents) => { + const staticKey = differentSocketKey ? randomBytes(32) : privateKey; + const channel = new ConnectChannel({ + role: 'responder', + hostId: identity.id, + staticKey, + ephemeralKey: randomBytes(32), + hostKey: noisePublicKey(staticKey), + }); + queueMicrotask(events.open); + return { + send(frame: string) { + wire.push(frame); + queueMicrotask(() => { + try { + const result = channel.receive(frame); + if (result.reply) events.message(result.reply); + if (result.message) { + const message = teamRecord(JSON.parse(result.message)); + messages.push(message); + if (message['type'] === 'owner-sign-in') + send({ + type: 'owner-signed-in', + result: { ok: true, value: { host: identity, deviceId, credential } }, + }); + if (message['type'] === 'admit' && message['credential'] === credential) + send({ type: 'admitted' }); + if (message['type'] === 'request') + send({ + type: 'response', + id: message['id'], + status: 200, + body: btoa('{"bots":[]}'), + }); + } + } catch { + events.closed('channel-handshake-rejected'); + } + }); + }, + close: () => channel.close(), + }; + function send(message: object) { + for (const reply of channel.send(JSON.stringify(message))) events.message(reply); + } + }); + const carrier: HostCarrier = { request, openSocket, randomBytes: () => randomBytes(32) }; + return { + carrier, + request, + openSocket, + messages, + wire, + encryption, + input: { carrier, route, username: 'owner', password, deviceName: 'Desktop' }, + }; +} + +describe('Owner password sign-in', () => { + it('validates the HTTPS discovery origin and sends credentials only inside an authenticated Noise channel', async () => { + const test = host(); + expect(await signInOwnerDevice(test.input)).toMatchObject({ + ok: true, + value: { + credential, + deviceId, + hostId: 'studio', + routes: [route], + encryption: { required: true, hostKey: test.encryption.publicKey }, + }, + }); + expect(test.request.mock.calls).toEqual([ + [ + route + '/botharness-device/channel', + { + method: 'GET', + redirect: 'error', + signal: expect.any(AbortSignal), + }, + ], + ]); + expect(test.openSocket.mock.calls[0]?.[0]).toBe( + 'wss://studio.example/botharness-device/channel', + ); + expect(test.messages).toEqual([ + expect.objectContaining({ + type: 'owner-sign-in', + input: { + username: 'owner', + password, + deviceName: 'Desktop', + fingerprint: test.encryption.fingerprint, + }, + }), + ]); + expect(test.wire.join('')).not.toContain(password); + }); + + it('refuses an origin whose saved Host public key changed before opening a socket', async () => { + const test = host(); + expect( + await signInOwnerDevice({ + ...test.input, + previous: () => ({ + hostId: 'studio', + hostName: 'Studio', + deviceId, + credential, + routes: [route], + encryption: { + protocol: 'connect-noise-xk-v1', + hostKey: '01'.repeat(32), + deviceKey: '02'.repeat(32), + }, + }), + }), + ).toEqual({ ok: false, code: 'fingerprint-mismatch' }); + expect(test.openSocket).not.toHaveBeenCalled(); + }); + + it('sends no credentials when the Noise peer cannot authenticate with the discovered key', async () => { + const test = host({ differentSocketKey: true }); + expect(await signInOwnerDevice(test.input)).toEqual({ + ok: false, + code: 'fingerprint-mismatch', + }); + expect(test.messages).toHaveLength(0); + }); + + it('preserves encrypted Owner access after saving a Tailscale or custom HTTPS route', async () => { + const test = host(); + const address = 'https://studio.tailnet.ts.net'; + const signed = await signInOwnerDevice({ ...test.input, route: address }); + if (!signed.ok) throw new Error(signed.code); + const saved = parseSavedHost(serializeSavedHost(signed.value)); + if (!saved) throw new Error('Saved Owner device required'); + const transport = encryptedCarrier({ ...saved, raw: test.carrier }); + try { + const response = await transport.request(address + '/botharness-device/api/botharness/list', { + method: 'POST', + signal: AbortSignal.timeout(3000), + }); + expect(await response.text()).toBe('{"bots":[]}'); + expect(test.request).toHaveBeenCalledOnce(); + expect(test.openSocket).toHaveBeenCalledTimes(2); + expect(test.messages).toContainEqual(expect.objectContaining({ type: 'admit', credential })); + expect(test.wire.join('')).not.toContain(credential); + } finally { + transport.close?.(); + } + }); + + it('does not use HTTP or continue after HTTPS discovery rejects', async () => { + const test = host(); + expect(await signInOwnerDevice({ ...test.input, route: 'http://studio.example' })).toEqual({ + ok: false, + code: 'insecure-transport', + }); + expect(test.request).not.toHaveBeenCalled(); + test.request.mockRejectedValueOnce(new TypeError('TLS certificate rejected')); + expect(await signInOwnerDevice(test.input)).toEqual({ ok: false, code: 'unreachable' }); + expect(test.openSocket).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/host-protocol/src/carrier.ts b/packages/host-protocol/src/carrier.ts index 530f55fe1e..6a62020a94 100644 --- a/packages/host-protocol/src/carrier.ts +++ b/packages/host-protocol/src/carrier.ts @@ -9,6 +9,7 @@ export interface HostResponse { export interface HostRequest { method: 'GET' | 'POST'; + redirect?: 'error'; body?: string | Blob; headers?: Record; signal: AbortSignal; diff --git a/packages/host-protocol/src/host-encryption.ts b/packages/host-protocol/src/host-encryption.ts index 3601eacbed..378cf19e5b 100644 --- a/packages/host-protocol/src/host-encryption.ts +++ b/packages/host-protocol/src/host-encryption.ts @@ -10,6 +10,7 @@ export interface PrivateAdmission { export interface HostEncryption { privateRelay?: PrivateAdmission; loopback?: 'encrypted'; + required?: true; protocol: 'connect-noise-xk-v1'; hostKey: string; deviceKey: string; diff --git a/packages/host-protocol/src/route.ts b/packages/host-protocol/src/route.ts index 3ee5a99fcd..0b094802c9 100644 --- a/packages/host-protocol/src/route.ts +++ b/packages/host-protocol/src/route.ts @@ -69,6 +69,15 @@ export function socketOrigin(origin: string): string { return origin.replace(/^http/u, 'ws'); } +export function isHttpsOrigin(input: string): boolean { + try { + const url = new URL(input); + return input.length <= 2048 && url.protocol === 'https:' && url.origin === input; + } catch { + return false; + } +} + export function isConnectRoute(route: string): boolean { try { return CONNECT_HOSTNAME.test(new URL(route).hostname); @@ -116,7 +125,11 @@ export function isPrivateRoute(route: string): boolean { } } -export function isEncryptedRoute(route: string, encryption?: { loopback?: 'encrypted' }): boolean { +export function isEncryptedRoute( + route: string, + encryption?: { loopback?: 'encrypted'; required?: true }, +): boolean { + if (encryption?.required) return true; if (isConnectRoute(route) || isLanRoute(route) || isPrivateRoute(route)) return true; return encryption?.loopback === 'encrypted' && isLoopbackRoute(route); } diff --git a/scripts/cli-ui-inventory.json b/scripts/cli-ui-inventory.json index fe7cccb985..6740b1f703 100644 --- a/scripts/cli-ui-inventory.json +++ b/scripts/cli-ui-inventory.json @@ -84,6 +84,15 @@ ], "issue": "#2097" }, + { + "id": "owner-password-sign-in", + "description": "Configure standalone Owner password sign-in and enroll a paired device through the authenticated encrypted channel.", + "scope": "Profile", + "surfaces": [ + "setting:packages/client/src/client/owner-password-sign-in-settings.tsx:{title}" + ], + "commands": ["team-mode", "device-owner-sign-in"] + }, { "id": "device-pairing", "description": "Device list, offers, offer status and revoke; the Connect tunnel action on the same route family has connect-status/enable/disable/sign-in/sign-out.", diff --git a/scripts/schema-migrations.json b/scripts/schema-migrations.json index 2804817ad3..df95362fd1 100644 --- a/scripts/schema-migrations.json +++ b/scripts/schema-migrations.json @@ -702,5 +702,9 @@ { "id": "role-engine-accounts", "sha256": "d818f03571a8220333a79b53b7b7db4243bf7ba60a8678a9647019773742987e" + }, + { + "id": "owner-password-sign-in", + "sha256": "cd24239ed9e9be52958c4f7a8436c1877dd00c40a4d7809d36df0b9d52e352d1" } ] From 76dc63c01c906f4dd721b9e92e5c94ddcea69ec1 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 03:23:37 +0900 Subject: [PATCH 02/16] Clarify verification for standalone Owner sign-in Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- .agents/skills/verify-deepseekbot/features/remote-hosts.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.agents/skills/verify-deepseekbot/features/remote-hosts.md b/.agents/skills/verify-deepseekbot/features/remote-hosts.md index 9dd1557e04..cd90de78d8 100644 --- a/.agents/skills/verify-deepseekbot/features/remote-hosts.md +++ b/.agents/skills/verify-deepseekbot/features/remote-hosts.md @@ -1,6 +1,6 @@ # Browser Remote Hosts -The browser reads each Remote Host Feed through its own Paired Device and the shared mobile Host client. Manual computer enrollment first establishes an explicitly approved reciprocal Host relationship; independent phone pairing stays separate. This Host remains the default management context. +The browser reads each Remote Host Feed through its own Paired Device and the shared Host client. Reciprocal enrollment starts with an approved Host Relationship. Standalone Owner password sign-in and independent phone pairing enroll their own devices. This Host is the default management context. ## Sources @@ -18,7 +18,7 @@ The browser reads each Remote Host Feed through its own Paired Device and the sh ## Standalone Owner password sign-in (#4898) -Use two fresh Profiles on the same build. Serve the target Host's device channel over a trusted HTTPS origin. For two Hosts on one machine, keep the source Web Client and target HTTPS gateway on different hostnames so their cookies stay scoped to their own hostnames. +Use two fresh Profiles on the same build. Serve the target Host's device channel over a trusted HTTPS origin. For two Hosts on one machine, keep the source Web Client and target HTTPS gateway on different hostnames so their cookies stay scoped to their own hostnames. The encrypted device gateway requires a cookie-free upgrade. If the browser attaches a target Host session cookie, use a fresh browser context for this journey. With Team mode off, open the target Host's Connections settings. Turn on **Password sign-in** and set an Owner username and password. In the source Owner Client, open **Add remote**, choose password sign-in, and enter the HTTPS address and credentials. Open a Channel unique to the target Host. Compare the visible Channel with the target CLI roster and the new exact device record. Check wrong credentials and an invalid or changed Host identity before the successful attempt. Record a clean console and an accessibility snapshot without credential fields. From a1c8cabeb4c5abe793ecc37efcdc9454232e9625 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 03:39:45 +0900 Subject: [PATCH 03/16] Use the Connections Back action for Owner sign-in Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- packages/client/src/client/owner-sign-in-dialog.tsx | 1 + packages/client/test/owner-sign-in-dialog.test.tsx | 3 +++ 2 files changed, 4 insertions(+) diff --git a/packages/client/src/client/owner-sign-in-dialog.tsx b/packages/client/src/client/owner-sign-in-dialog.tsx index 78dbb6e1e6..0c10ece5dc 100644 --- a/packages/client/src/client/owner-sign-in-dialog.tsx +++ b/packages/client/src/client/owner-sign-in-dialog.tsx @@ -97,6 +97,7 @@ export function OwnerSignInDialog({ title={t('ownerSignIn.title')} description={t('ownerSignIn.hint')} inline={inline} + showCancel={!inline} footerContainer={footerContainer} labels={{ close: t('common.close'), cancel: t('connections.back') }} submitLabel={t('teamSignIn.signIn')} diff --git a/packages/client/test/owner-sign-in-dialog.test.tsx b/packages/client/test/owner-sign-in-dialog.test.tsx index b6dd82c923..f6d5964b72 100644 --- a/packages/client/test/owner-sign-in-dialog.test.tsx +++ b/packages/client/test/owner-sign-in-dialog.test.tsx @@ -33,6 +33,9 @@ it('signs in from one form, gives one invalid-credentials error, and clears the await act(async () => root.render(), ); + expect( + [...container.querySelectorAll('button')].map((button) => button.textContent), + ).not.toContain(zhTranslate('connections.back')); const password = container.querySelector('input[type="password"]'); const submit = container.querySelector('button[type="submit"]'); await act(async () => { From 01e9ca5d0acdc3a8a68aa8f13a19c178462637ef Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 04:53:55 +0900 Subject: [PATCH 04/16] Keep Owner password settings in the Team authentication module Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- packages/core/src/team/member-auth.ts | 72 +++++++++++++++++++++++++-- packages/core/src/team/service.ts | 66 +++--------------------- 2 files changed, 76 insertions(+), 62 deletions(-) diff --git a/packages/core/src/team/member-auth.ts b/packages/core/src/team/member-auth.ts index d9c27ce090..b2eb5c1a93 100644 --- a/packages/core/src/team/member-auth.ts +++ b/packages/core/src/team/member-auth.ts @@ -56,6 +56,7 @@ export type MemberAuthHost = { deviceGrantResult: TeamService['deviceGrantResult']; ensureTob: TeamService['ensureTob']; invalidate: TeamService['invalidate']; + hasCredential: TeamService['hasCredential']; isOwner: TeamService['isOwner']; limiter: TeamService['limiter']; log: TeamService['log']; @@ -63,7 +64,7 @@ export type MemberAuthHost = { member: TeamService['member']; memberDevices: TeamService['memberDevices']; now: TeamService['now']; - ownerPasswordEnabled: TeamService['ownerPasswordEnabled']; + owner: TeamService['owner']; pairing: TeamService['pairing']; passwordAttempt: TeamService['passwordAttempt']; passwordCaller: TeamService['passwordCaller']; @@ -124,6 +125,71 @@ export async function signIn( return { ...this.createGrant(member, device), member }; } +function ownerPasswordEnabled(db: MemberAuthHost['db']): boolean { + return db.read( + (db) => + db.prepare('SELECT owner_password_sign_in FROM team_settings WHERE singleton = 1').get() + ?.owner_password_sign_in === 1, + ); +} + +export function ownerPasswordSignIn( + this: MemberAuthHost, + human: HumanContext, +): { enabled: boolean; username?: string } { + this.owner(human); + const username = this.credential(human.humanId)?.username; + return { + enabled: ownerPasswordEnabled(this.db), + ...(username === undefined ? {} : { username }), + }; +} + +export async function ownerPasswordSignInSet( + this: MemberAuthHost, + human: HumanContext, + input: { enabled: boolean; username?: string | undefined; password?: string | undefined }, +): Promise<{ enabled: boolean; username?: string }> { + const previous = ownerPasswordSignIn.call(this, human); + const { enabled, username, password } = input; + if (enabled && previous.username === undefined) { + if (username === undefined || password === undefined) + throw new TeamError('owner-password-required'); + if (!/^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username)) throw new TeamError('username-invalid'); + if (!strongPassword(password)) throw new TeamError('password-weak'); + if (this.byUsername(username)) throw new TeamError('username-taken'); + const hash = await hashPassword(password); + this.owner(human); + if (this.hasCredential(human.humanId)) throw new TeamError('invalid-input'); + if (this.byUsername(username)) throw new TeamError('username-taken'); + this.db.transaction( + (db) => { + db.prepare('INSERT INTO member_credentials VALUES (?, ?, ?, ?, 0)').run( + human.humanId, + username, + credentialPasswordJson(hash, human.humanId), + '[]', + ); + db.prepare('UPDATE team_settings SET owner_password_sign_in = 1 WHERE singleton = 1').run(); + }, + ['team'], + ); + } else { + if (username !== undefined || password !== undefined) throw new TeamError('invalid-input'); + if (previous.enabled === enabled) return previous; + this.db.transaction( + (db) => + db + .prepare('UPDATE team_settings SET owner_password_sign_in = ? WHERE singleton = 1') + .run(Number(enabled)), + ['team'], + ); + } + this.invalidate(); + this.log('owner-password-sign-in-changed', { initiator: 'owner', enabled }); + return ownerPasswordSignIn.call(this, human); +} + export async function signInOwnerDevice( this: MemberAuthHost, username: string, @@ -131,14 +197,14 @@ export async function signInOwnerDevice( ip: string, issue: (humanId: string) => T, ): Promise { - if (!this.ownerPasswordEnabled()) throw new TeamError('owner-sign-in-disabled'); + if (!ownerPasswordEnabled(this.db)) throw new TeamError('owner-sign-in-disabled'); this.passwordAttempt(username, ip); const { humanId } = this.roles.ownerContext(); const credential = this.credential(humanId); const matches = credential?.username === username; const valid = await verifyPassword(password, matches ? credential.hash : DUMMY_PASSWORD_HASH); if (!matches || !valid) throw new TeamError('credentials-invalid'); - if (!this.ownerPasswordEnabled()) throw new TeamError('owner-sign-in-disabled'); + if (!ownerPasswordEnabled(this.db)) throw new TeamError('owner-sign-in-disabled'); if ( this.roles.ownerContext().humanId !== humanId || this.credential(humanId)?.hash.hash !== credential.hash.hash diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts index 8972ec971d..707800f876 100644 --- a/packages/core/src/team/service.ts +++ b/packages/core/src/team/service.ts @@ -218,6 +218,7 @@ export class TeamService { get ensureTob() { return service.ensureTob?.bind(service); }, + hasCredential: (...args) => service.hasCredential(...args), invalidate: (...args) => service.invalidate(...args), isOwner: (...args) => service.isOwner(...args), get limiter() { @@ -230,7 +231,6 @@ export class TeamService { now: (...args) => service.now(...args), ownedBots: (...args) => service.ownedBots(...args), owner: (...args) => service.owner(...args), - ownerPasswordEnabled: (...args) => service.ownerPasswordEnabled(...args), pairedIds: (...args) => service.pairedIds(...args), get pairing() { return service.pairing; @@ -547,67 +547,15 @@ export class TeamService { throw new TeamError('permission-required', undefined, { permission: 'owner' }); } - private ownerPasswordEnabled(): boolean { - return this.db.read( - (db) => - db.prepare('SELECT owner_password_sign_in FROM team_settings WHERE singleton = 1').get() - ?.owner_password_sign_in === 1, - ); + ownerPasswordSignIn(human: HumanContext) { + return memberAuth.ownerPasswordSignIn.call(this.#memberOperations, human); } - ownerPasswordSignIn(human: HumanContext): { enabled: boolean; username?: string } { - this.owner(human); - const username = this.credential(human.humanId)?.username; - return { - enabled: this.ownerPasswordEnabled(), - ...(username === undefined ? {} : { username }), - }; - } - - async ownerPasswordSignInSet( + ownerPasswordSignInSet( human: HumanContext, - input: { enabled: boolean; username?: string | undefined; password?: string | undefined }, - ): Promise<{ enabled: boolean; username?: string }> { - const previous = this.ownerPasswordSignIn(human); - const { enabled, username, password } = input; - if (enabled && previous.username === undefined) { - if (username === undefined || password === undefined) - throw new TeamError('owner-password-required'); - if (!/^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username)) throw new TeamError('username-invalid'); - if (!strongPassword(password)) throw new TeamError('password-weak'); - if (this.byUsername(username)) throw new TeamError('username-taken'); - const hash = await hashPassword(password); - this.owner(human); - if (this.hasCredential(human.humanId)) throw new TeamError('invalid-input'); - if (this.byUsername(username)) throw new TeamError('username-taken'); - this.db.transaction( - (db) => { - db.prepare('INSERT INTO member_credentials VALUES (?, ?, ?, ?, 0)').run( - human.humanId, - username, - credentialPasswordJson(hash, human.humanId), - '[]', - ); - db.prepare( - 'UPDATE team_settings SET owner_password_sign_in = 1 WHERE singleton = 1', - ).run(); - }, - ['team'], - ); - } else { - if (username !== undefined || password !== undefined) throw new TeamError('invalid-input'); - if (previous.enabled === enabled) return previous; - this.db.transaction( - (db) => - db - .prepare('UPDATE team_settings SET owner_password_sign_in = ? WHERE singleton = 1') - .run(Number(enabled)), - ['team'], - ); - } - this.invalidate(); - this.log('owner-password-sign-in-changed', { initiator: 'owner', enabled }); - return this.ownerPasswordSignIn(human); + input: Parameters[1], + ) { + return memberAuth.ownerPasswordSignInSet.call(this.#memberOperations, human, input); } async setMode(human: HumanContext, enabled: boolean): Promise { From 957aca0c5f05c1157290ccad59dd61716258ea7c Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 05:19:00 +0900 Subject: [PATCH 05/16] Cover Owner sign-in endpoints in the bridge inventory Issue: #4898 Agent-Task: codex/local/01a1ffa6-e6a0-75a0-bb06-711b17edf1f7 --- packages/core/test/bridge-method-inventory.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/core/test/bridge-method-inventory.ts b/packages/core/test/bridge-method-inventory.ts index 489fc1de9a..0e7e5fac4f 100644 --- a/packages/core/test/bridge-method-inventory.ts +++ b/packages/core/test/bridge-method-inventory.ts @@ -20,6 +20,8 @@ export const bridgeMethodInventory = [ 'modelsAllowed', 'usageByMember', 'teamModeSet', + 'ownerPasswordSignIn', + 'ownerPasswordSignInSet', 'teamOwnerPasswordSet', 'teamInsecureHttpSet', 'members', From 4b9c0b65149db6cfda03ce36d307ef90e1750f11 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 05:23:32 +0900 Subject: [PATCH 06/16] Assert legacy device enrollment after schema migration Issue: #4898 Agent-Task: codex/local/01a1ffa6-e6a0-75a0-bb06-711b17edf1f7 --- packages/core/test/schema-main-e6.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/core/test/schema-main-e6.test.ts b/packages/core/test/schema-main-e6.test.ts index ebbc997137..89a6f23567 100644 --- a/packages/core/test/schema-main-e6.test.ts +++ b/packages/core/test/schema-main-e6.test.ts @@ -79,8 +79,9 @@ it('appends account150 after published Team models148 and usage149 while preserv 'suspended', ); }); + const pairedDevicesSql = 'SELECT * FROM paired_devices ORDER BY device_id'; + const legacyDevices = database.read((db) => db.prepare(pairedDevicesSql).all()); const tables = [ - 'paired_devices', 'relationship_device_grants', 'humans', 'team_mode_suspensions', @@ -111,6 +112,9 @@ it('appends account150 after published Team models148 and usage149 while preserv expect(owner.mode).toBe('ready'); expect(owner.generation).toBe(BOT_HARNESS_SCHEMA_PLAN.targetGeneration); const current = attachOperationalModule(owner, 'migration-fixture'); + expect(current.read((db) => db.prepare(pairedDevicesSql).all())).toEqual( + legacyDevices.map((device) => ({ ...device, enrollment: null })), + ); expect( current.read((db) => Object.fromEntries( From 0ceb21f4a0418299799770cbd15c573aacb81e7a Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 05:41:03 +0900 Subject: [PATCH 07/16] Revoke other password-enrolled Owner devices on password change Issue: #4899 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- .../features/remote-hosts.md | 6 ++ .../4899-owner-password-device-revocation.md | 11 +++ .../botharness-architecture.en.md | 2 + docs/architecture/botharness-architecture.md | 2 + docs/bot-cli.md | 2 + docs/bot-cli.zh.md | 2 + .../client/src/client/features/team/locale.ts | 2 + .../src/client/settings-environment.tsx | 59 +++++++++++- packages/client/src/client/team-bridge.ts | 2 + packages/client/src/client/team-settings.tsx | 24 ++++- .../owner-password-sign-in-settings.test.tsx | 26 +++++ packages/core/src/bots/cli-team.ts | 11 ++- packages/core/src/bridge/rpc.ts | 4 +- packages/core/src/devices/gateway.ts | 14 ++- packages/core/src/devices/mount-gateway.ts | 12 +++ packages/core/src/features/team/rpc.ts | 3 +- packages/core/src/team/bridge.ts | 19 +++- packages/core/src/team/http.ts | 37 ++++++-- packages/core/src/team/member-auth.ts | 68 +++++++++++++ packages/core/src/team/service.ts | 33 ++----- packages/core/test/cli-team.test.ts | 22 +++++ .../owner-password-device-sign-in.test.ts | 95 +++++++++++++++++++ 22 files changed, 403 insertions(+), 53 deletions(-) create mode 100644 changes/4899-owner-password-device-revocation.md diff --git a/.agents/skills/verify-deepseekbot/features/remote-hosts.md b/.agents/skills/verify-deepseekbot/features/remote-hosts.md index cd90de78d8..9e7158b00a 100644 --- a/.agents/skills/verify-deepseekbot/features/remote-hosts.md +++ b/.agents/skills/verify-deepseekbot/features/remote-hosts.md @@ -24,6 +24,12 @@ With Team mode off, open the target Host's Connections settings. Turn on **Passw Use `team-mode owner-sign-in status` to inspect the setting. Sign in a separate CLI device with `device-owner-sign-in` and validate `device-probe` with its private device file. Disable password sign-in on the target. Verify that a new login is refused and both enrolled devices still read the target Feed. Revoke the CLI device by its ID and verify it loses access. Restart the target Profile and verify the setting and selected username persist. Remove test device files during cleanup. +## Change the Owner password (#4899) + +On a fresh Host with Team mode off, enroll two Owner devices by password and one by QR code. On the first device, open the target **Host settings → Connections → Your password → Change**. On the Host itself, use **Settings → Team → Your password → Change**. Confirm the sign-out checkbox defaults to selected. Save the new password. The other password-enrolled device loses its live connection and its next authenticated read is refused. The device that changed the password and the QR-paired device still read the target Host Feed. Verify the old password is refused for new sign-ins and the new password works. Repeat with the checkbox cleared and verify all existing devices keep their access. + +For CLI parity, pass the private JSON containing `current` and `password` on stdin to `team-mode owner-password --password-stdin --sign-out-others=true --confirm`. Compare `devices` and `device-probe` results for password and QR grants, and repeat with `--sign-out-others=false`. Redact credentials from visual and console evidence. + ## Reciprocal relationship (E1) Use fresh schema144 Homes after published Team141–143; do not launch internal Environment141–143 preview databases with this source. Relationship management is current-Owner-only: member/Admin HTTP carriers and CLI `--as` must refuse list/initiate/approve/enroll/disconnect. Transfer Owner and require old derived credentials and pending old-Owner offers to refuse; a newly enrolled Client records the new Owner Human. A valid current-Owner credential still cannot bypass inactive-relationship admission. Retain private Source Event Human readback, spoofed Human rejection and private-Bot access refusals through the same per-Human bridge factory. diff --git a/changes/4899-owner-password-device-revocation.md b/changes/4899-owner-password-device-revocation.md new file mode 100644 index 0000000000..270ff661e1 --- /dev/null +++ b/changes/4899-owner-password-device-revocation.md @@ -0,0 +1,11 @@ +--- +section: Added +--- + +## en + +- When Host Owners change their password, they can sign out other devices enrolled by password. The current device and QR-paired devices retain access ([#4899](https://github.com/BotHarness/DeepSeekBot/issues/4899)). + +## zh + +- Host Owner 更改密码时可退出其他通过账密登录的设备。当前设备和扫码配对设备可继续访问([#4899](https://github.com/BotHarness/DeepSeekBot/issues/4899))。 diff --git a/docs/architecture/botharness-architecture.en.md b/docs/architecture/botharness-architecture.en.md index a322d25100..1e5702c412 100644 --- a/docs/architecture/botharness-architecture.en.md +++ b/docs/architecture/botharness-architecture.en.md @@ -72,6 +72,8 @@ Desktop, iOS, and Android share the Host identity and password sign-in flow when The Host issues a Paired Device grant for the authenticated Human and binds it to the Client device key. The existing Devices module owns the grant and records its issuance method for selective revocation during Owner password changes. Team mode enables password sign-in. With Team mode off, the standalone Owner setting controls new Owner password sign-ins. The first delivery covers standalone Owner sign-in over HTTPS in desktop and Web Clients. See [connection decisions](../decisions/connections.md#remote-host-password-sign-in-uses-the-same-encrypted-device-channel-on-every-route) and [Team mode decisions](../decisions/team-mode.md#host-password-sign-in-and-team-mode). +When the Owner chooses to sign out other devices during a password change, the Team Service commits the new password and targeted revocations together. The device gateway supplies the current device from its authenticated connection. The Devices module then closes the revoked connections. + ## 1 · System context ```mermaid diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md index ed0c83a1fa..5058a52db2 100644 --- a/docs/architecture/botharness-architecture.md +++ b/docs/architecture/botharness-architecture.md @@ -660,6 +660,8 @@ The application-defined `ConnectionsDialog` presents pairing and device manageme Host 按当前 Human 身份签发与客户端设备公钥绑定的 Paired Device 授权。设备授权由现有设备模块持有,并记录签发方式,供 Owner 改密时选择性撤销。Team mode 自动开启账密登录。Team mode 关闭后,Host 根据独立的 Owner 设置决定是否接收新的 Owner 账密登录。见[连接决策](../decisions/connections.md#remote-host-password-sign-in-uses-the-same-encrypted-device-channel-on-every-route)和 [Team mode 决策](../decisions/team-mode.md#host-password-sign-in-and-team-mode)。 +Owner 改密时若选择退出其他设备,Team Service 在同一事务中保存新密码并撤销指定授权。设备网关从已认证连接取得当前设备,设备模块在提交后关闭已撤销的连接。 + ### 手机推送 [ADR-0202](../decisions/mobile.md#adr-0202)([#1655](https://github.com/BotHarness/DeepSeekBot/issues/1655)):应用定义的 Push delivery 模块(`packages/core/src/push/`)是 Activity 的投影,不另设通知权威。Activity 表或 PersonaBot 的审批、提问、私密输入计数变化时(以及每分钟一次的兜底扫描),模块读取 `action` 项与未读的 `replies` 项,对每台已登记的配对设备只发送一次新项,并经 Expo Push Service 投递;推送标题为频道名(`#名称`,私信为 PersonaBot 名称),正文为所需操作加上工具与主要参数、问题或消息的简短预览(折叠空白,预览最多 140 个 UTF-16 代码单元,含截断省略号);私密输入请求不含内容([ADR-0213](../decisions/mobile.md#adr-0213))。数据字段包含路由标识、显示文字及适用的发送者和审批元数据。由 Android 原生模块呈现的通知也从数据字段读取标题、正文和角标。角标表示该 Host 的未处理 Human 操作数。设备经设备网关的 `/botharness-device/push` 登记 Expo push token、切换各类通知、发送测试通知;撤销设备或 Expo 回报 `DeviceNotRegistered` 时删除 token。发送失败有界重试,结果写入不含内容的 `push` 开发者日志。App 保存每台配对的 Host,点按通知先切换到对应 Host,再打开该审批、提问或私信。 diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 5dd2412cee..aa4ed7de1a 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -2263,6 +2263,8 @@ QQ also supports `deepseekbot messaging-defaults qq` and `messaging-defaults-set Use `team-mode owner-sign-in status` to read the standalone Owner sign-in setting on the selected Host. To create the first credential, run `team-mode owner-sign-in on --username --password-stdin --confirm` with the password on stdin. To reuse a configured credential, run `team-mode owner-sign-in on --confirm`. The `off` action stops new password sign-ins and keeps existing Owner devices connected. +To change an existing Owner password, pass a private JSON file containing the `current` and `password` fields on stdin to `team-mode owner-password --password-stdin`. Add `--sign-out-others=true --confirm` to revoke the other Owner devices enrolled by password. QR-paired devices and the active Owner session retain access. With the flag omitted or set to `false`, existing devices retain access. + On another Client, use `device-owner-sign-in --password-stdin --confirm --out `. The CLI validates the HTTPS origin and sends the password through the authenticated encrypted device channel. It writes keys and credentials to the new private file and prints the Host ID, device ID, and output path. Use `device-probe --device-file ` to read the real Host Feed with that device grant. `dm ` opens or creates the authenticated Human's canonical DM with that active person on the selected Host. Opening from either participant returns the same Channel; another Human's DM remains inaccessible. Use `channels send --body-stdin` and `channel-messages ` for messages. Pure Human DMs have no Bot participant; Group messages remain readable by their eligible Bot members. diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index f1dfb5dec5..e25a84b2d3 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -2181,6 +2181,8 @@ QQ 同样支持 `deepseekbot messaging-defaults qq` 和 `messaging-defaults-set 使用 `team-mode owner-sign-in status` 查看目标 Host 的独立 Owner 账密登录设置。首次创建账密时执行 `team-mode owner-sign-in on --username <用户名> --password-stdin --confirm`,通过标准输入提供密码。已有账密时,执行 `team-mode owner-sign-in on --confirm` 即可继续使用。用 `off` 停止新的账密登录,已登记的 Owner 设备可以继续连接。 +更改现有 Owner 密码时,把含有 `current` 和 `password` 字段的私有 JSON 文件通过标准输入传给 `team-mode owner-password --password-stdin`。添加 `--sign-out-others=true --confirm` 可撤销其他通过账密登记的 Owner 设备。扫码配对设备和当前 Owner 会话可继续访问。省略该选项或设为 `false` 时,已有设备可继续访问。 + 在另一端执行 `device-owner-sign-in <可信 HTTPS 地址> <用户名> --password-stdin --confirm --out <私有设备文件绝对路径>`。CLI 验证 HTTPS 地址,经已认证的设备加密通道提交密码,将设备密钥和凭据写入新建的私有文件。标准输出只报告 Host ID、设备 ID 和文件路径等连接信息。使用 `device-probe --device-file <私有设备文件绝对路径>` 验证可用该设备授权读取真实 Host Feed。 `dm ` 在指定 Host 上打开或创建当前 Human 与该活跃联系人的唯一私聊。双方打开会返回同一频道,其他 Human 无权读取。使用 `channels send --body-stdin` 和 `channel-messages ` 收发、读取消息。纯 Human 私聊没有 Bot 参与者;群消息仍可由有权参与的 Bot 阅读。 diff --git a/packages/client/src/client/features/team/locale.ts b/packages/client/src/client/features/team/locale.ts index 0440581ae0..0bdcff7706 100644 --- a/packages/client/src/client/features/team/locale.ts +++ b/packages/client/src/client/features/team/locale.ts @@ -58,6 +58,7 @@ export const zh = { 'team.ownerPassword.change': '更改', 'team.ownerPassword.setupTitle': '设置你的密码', 'team.ownerPassword.changeTitle': '更改你的密码', + 'team.ownerPassword.signOutOthers': '退出其他通过账密登录的设备', 'team.ownerPassword.hint': '在这台电脑上打开仍不需要密码。', 'team.ownerPassword.enableHint': '开启团队模式前需要先设置密码。在这台电脑上打开仍不需要密码。', 'team.ownerPassword.saveAndEnable': '保存并开启', @@ -457,6 +458,7 @@ export const en = { 'team.ownerPassword.change': 'Change', 'team.ownerPassword.setupTitle': 'Set your password', 'team.ownerPassword.changeTitle': 'Change your password', + 'team.ownerPassword.signOutOthers': 'Sign out other devices that used your password', 'team.ownerPassword.hint': 'This computer still opens without it.', 'team.ownerPassword.enableHint': 'Team mode needs your password first. This computer still opens without it.', diff --git a/packages/client/src/client/settings-environment.tsx b/packages/client/src/client/settings-environment.tsx index f4a9aab100..8a27b7499d 100644 --- a/packages/client/src/client/settings-environment.tsx +++ b/packages/client/src/client/settings-environment.tsx @@ -1,10 +1,12 @@ -import { useMemo, useRef, type ReactElement } from 'react'; +import { useMemo, useRef, useState, type ReactElement } from 'react'; import type { HostClient } from '@botharness/host-client/client'; import { shownHostName } from '@botharness/host-client/ui/design/host-look'; import { Note } from './ds/note.js'; +import { Button } from './ds/button.js'; import { Select } from './ds/select.js'; +import { SettingsRow } from './ds/settings-row.js'; import { useHostLook } from './host-looks.js'; import type { BotHarnessTranslate } from './locale.js'; import { RemoteHostModels } from './remote-host-models.js'; @@ -21,6 +23,8 @@ import { RemoteMessagingSettings } from './remote-messaging-settings.js'; import { StorageSettings } from './storage-settings.js'; import type { RemoteHosts } from './remote-hosts.js'; import { TargetName } from './target-name.js'; +import { loadTeamMode, setOwnerPassword } from './team-bridge.js'; +import { OwnerPasswordDialog } from './team-settings.js'; export type SettingsEnvironments = Pick< RemoteHosts, @@ -115,7 +119,16 @@ export function RemoteEnvironmentSection({ /> ); if (section === REMOTE_SETTINGS_SECTIONS.hostConnections) - return remote === undefined ? offline : ; + return remote === undefined ? ( + offline + ) : ( + <> + + {connected && client !== undefined && remote.host.member === undefined ? ( + + ) : null} + + ); if (section === REMOTE_SETTINGS_SECTIONS.hostModels) { if (shownClient === undefined) return offline; return ( @@ -135,6 +148,48 @@ export function RemoteEnvironmentSection({ return ; } +function RemoteOwnerPassword({ client, t }: { client: HostClient; t: BotHarnessTranslate }) { + const { call } = remoteHostSettings(client); + const [available, setAvailable] = useState(false); + const [open, setOpen] = useState(false); + const mount = useMountedResource(() => { + const controller = new AbortController(); + setAvailable(false); + void loadTeamMode(call, controller.signal) + .then((view) => { + if (!controller.signal.aborted) setAvailable(view.viewer.owner && view.ownerPasswordSet); + }) + .catch(() => {}); + return () => controller.abort(); + }, [call]); + return ( +
+ {available ? ( + setOpen(true)}> + {t('team.ownerPassword.change')} + + } + /> + ) : null} + {available && open ? ( + setOpen(false)} + onSubmit={async (password, current, signOutOthers) => { + await setOwnerPassword(call, password, current, signOutOthers); + setOpen(false); + }} + /> + ) : null} +
+ ); +} + export function LocalHostAppearance({ hostId, name, diff --git a/packages/client/src/client/team-bridge.ts b/packages/client/src/client/team-bridge.ts index f022977428..e597b82d6f 100644 --- a/packages/client/src/client/team-bridge.ts +++ b/packages/client/src/client/team-bridge.ts @@ -228,11 +228,13 @@ export async function setOwnerPassword( call: BridgeCall, password: string, current?: string, + signOutOthers?: boolean, ): Promise { return parseTeamMode( await unwrap(call, 'teamOwnerPasswordSet', { password, ...(current === undefined ? {} : { current }), + ...(signOutOthers === undefined ? {} : { signOutOthers }), }), ); } diff --git a/packages/client/src/client/team-settings.tsx b/packages/client/src/client/team-settings.tsx index a485153430..d393c12b3b 100644 --- a/packages/client/src/client/team-settings.tsx +++ b/packages/client/src/client/team-settings.tsx @@ -1,4 +1,5 @@ import { Button } from './ds/button.js'; +import { Checkbox } from './ds/checkbox.js'; import { Switch } from './ds/switch.js'; import { useRef, useState, type ReactElement } from 'react'; import * as stylex from '@stylexjs/stylex'; @@ -542,9 +543,9 @@ export function TeamSection({ call, t }: TeamSectionProps): ReactElement { passwordSaved.current = false; setDialog(undefined); }} - onSubmit={async (password, current) => { + onSubmit={async (password, current, signOutOthers) => { if (!passwordSaved.current) { - publish(await setOwnerPassword(call, password, current)); + publish(await setOwnerPassword(call, password, current, signOutOthers)); passwordSaved.current = true; } if (dialog.thenEnable) publish(await setTeamMode(call, true)); @@ -613,7 +614,7 @@ function memberMeta( return parts.join(' · '); } -function OwnerPasswordDialog({ +export function OwnerPasswordDialog({ t, hasPassword, thenEnable, @@ -624,11 +625,12 @@ function OwnerPasswordDialog({ hasPassword: boolean; thenEnable: boolean; onCancel(): void; - onSubmit(password: string, current: string | undefined): Promise; + onSubmit(password: string, current?: string, signOutOthers?: boolean): Promise; }): ReactElement { const [current, setCurrent] = useState(''); const [password, setPassword] = useState(''); const [confirm, setConfirm] = useState(''); + const [signOutOthers, setSignOutOthers] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(); const short = password.length > 0 && password.length < TEAM_PASSWORD_MIN_LENGTH; @@ -650,7 +652,11 @@ function OwnerPasswordDialog({ onSubmit={() => { setBusy(true); setError(undefined); - onSubmit(password, hasPassword ? current : undefined) + onSubmit( + password, + hasPassword ? current : undefined, + hasPassword ? signOutOthers : undefined, + ) .catch((failure: unknown) => setError(teamErrorText(t, failure))) .finally(() => setBusy(false)); }} @@ -686,6 +692,14 @@ function OwnerPasswordDialog({ onChange={setConfirm} error={mismatch ? t('team.password.mismatch') : undefined} /> + {hasPassword ? ( + + ) : null} ); diff --git a/packages/client/test/owner-password-sign-in-settings.test.tsx b/packages/client/test/owner-password-sign-in-settings.test.tsx index 38d07e965d..a1966031af 100644 --- a/packages/client/test/owner-password-sign-in-settings.test.tsx +++ b/packages/client/test/owner-password-sign-in-settings.test.tsx @@ -6,6 +6,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import type { BridgeCall } from '../src/client/bridge.js'; import { ConnectionsPage } from '../src/client/connections-dialog.js'; import { zhTranslate } from '../src/client/locale.js'; +import { OwnerPasswordDialog } from '../src/client/team-settings.js'; vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({ ...(await import('./primitive-mocks.js')).shellPrimitives(), @@ -67,6 +68,31 @@ function signInSwitch(): HTMLButtonElement { return toggle; } +it.each([true, false])('submits the selected Owner device sign-out choice %s', async (signOut) => { + const submit = vi.fn(async () => {}); + await act(async () => + root.render( + {}} + onSubmit={submit} + />, + ), + ); + const checkbox = field(zhTranslate('team.ownerPassword.signOutOthers')); + expect(checkbox.checked).toBe(true); + if (!signOut) await act(async () => checkbox.click()); + await fill(zhTranslate('team.password.current'), 'current-owner-password'); + await fill(zhTranslate('team.password.new'), 'next-owner-password'); + await fill(zhTranslate('team.password.confirm'), 'next-owner-password'); + const dialog = document.querySelector('[role="dialog"]'); + if (!dialog) throw new Error('Missing Owner password dialog'); + await act(async () => button(zhTranslate('team.save'), dialog).click()); + expect(submit).toHaveBeenCalledWith('next-owner-password', 'current-owner-password', signOut); +}); + it('sets up sign-in, then toggles it without re-entering credentials', async () => { let configured = false; let enabled = false; diff --git a/packages/core/src/bots/cli-team.ts b/packages/core/src/bots/cli-team.ts index df39942fab..5c5decb8bb 100644 --- a/packages/core/src/bots/cli-team.ts +++ b/packages/core/src/bots/cli-team.ts @@ -45,7 +45,7 @@ export const TEAM_COMMANDS = [ { command: 'team-mode', description: - 'status | on | off | owner-password --password-stdin | owner-sign-in status|on|off | insecure-http on|off --confirm | transfer-owner --password-stdin --confirm', + 'status | on | off | owner-password --password-stdin [--sign-out-others=true --confirm] | owner-sign-in status|on|off | insecure-http on|off --confirm | transfer-owner --password-stdin --confirm', }, { command: 'members', @@ -388,11 +388,18 @@ export async function runTeamCommand( if ((action === 'on' || action === 'off') && rest.length === 1) return rpc('teamModeSet', { enabled: action === 'on' }); if (action === 'owner-password' && values['password-stdin'] && rest.length === 1) { + const signOut = values['sign-out-others']; + if (signOut !== undefined && signOut !== 'true' && signOut !== 'false') return usage(); + if (signOut === 'true' && !values.confirm) + throw new CliLiveError('confirm-required', 'Signing out other devices requires --confirm.'); const text = await secret(io); const input = text.startsWith('{') ? secretJson(z.object({ password: z.string(), current: z.string().optional() }), text) : { password: text }; - return rpc('teamOwnerPasswordSet', input); + return rpc('teamOwnerPasswordSet', { + ...input, + ...(signOut === undefined ? {} : { signOutOthers: signOut === 'true' }), + }); } if ( action === 'insecure-http' && diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index 8df62938ec..af2de20bbd 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -504,8 +504,8 @@ export class BotharnessBridgeService extends TypertRemoteService { ownerPasswordSignInSet(enabled: boolean, username?: string, password?: string) { return teamRpc.ownerPasswordSignInSet(this.methods, enabled, username, password); } - teamOwnerPasswordSet(password: string, current?: string) { - return teamRpc.teamOwnerPasswordSet(this.methods, password, current); + teamOwnerPasswordSet(password: string, current?: string, signOutOthers?: boolean) { + return teamRpc.teamOwnerPasswordSet(this.methods, password, current, signOutOthers); } teamInsecureHttpSet(allowed: boolean) { return teamRpc.teamInsecureHttpSet(this.methods, allowed); diff --git a/packages/core/src/devices/gateway.ts b/packages/core/src/devices/gateway.ts index 11eb5c1a1f..2ce80b59a9 100644 --- a/packages/core/src/devices/gateway.ts +++ b/packages/core/src/devices/gateway.ts @@ -392,11 +392,8 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa if (!admission.ok) return refuse(response, 401, admission.code); const pathname = new URL(request.url ?? '/', 'http://device').pathname; const endpoint = pathname.slice(`${prefix}/api/`.length); - if ( - decodeURIComponent(endpoint) - .replace(/\/{2,}/gu, '/') - .startsWith('botharness/relationships') - ) + const normalizedEndpoint = decodeURIComponent(endpoint).replace(/\/{2,}/gu, '/'); + if (normalizedEndpoint.startsWith('botharness/relationships')) return refuse(response, 403, 'relationship-local-client-required'); if ( await refuseConnectRpc(request, response, endpoint, () => @@ -404,6 +401,13 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa ) ) return; + if ( + admission.device.enrollment === 'owner-password' && + normalizedEndpoint.replace(/\/$/u, '') === 'botharness/teamOwnerPasswordSet' + ) { + if (!options.team) return refuse(response, 503, 'host-session-unavailable'); + return options.team.ownerDevicePassword(request, response, admission.device.id); + } let session: string; try { session = await hostSession(); diff --git a/packages/core/src/devices/mount-gateway.ts b/packages/core/src/devices/mount-gateway.ts index 569308e44d..b1010ea4f0 100644 --- a/packages/core/src/devices/mount-gateway.ts +++ b/packages/core/src/devices/mount-gateway.ts @@ -97,6 +97,18 @@ export function mountDeviceGateway( get device() { return memberGateway?.device; }, + async ownerDevicePassword( + request: IncomingMessage, + response: ServerResponse, + deviceId: string, + ) { + if (memberGateway) return memberGateway.ownerDevicePassword(request, response, deviceId); + response.writeHead(503, { + 'content-type': 'application/json', + 'cache-control': 'no-store', + }); + response.end(JSON.stringify({ code: 'member-carrier-unavailable' })); + }, async handle(request: IncomingMessage, response: ServerResponse) { if (memberGateway) return memberGateway.handle(request, response); response.writeHead(503, { diff --git a/packages/core/src/features/team/rpc.ts b/packages/core/src/features/team/rpc.ts index a58662bfab..fdf2ec5fc8 100644 --- a/packages/core/src/features/team/rpc.ts +++ b/packages/core/src/features/team/rpc.ts @@ -141,8 +141,9 @@ export function teamOwnerPasswordSet( methods: TeamBridgeMethods, password: string, current?: string, + signOutOthers?: boolean, ) { - return unwrapAsync(methods.teamOwnerPasswordSet({ password, current })); + return unwrapAsync(methods.teamOwnerPasswordSet({ password, current, signOutOthers })); } export function teamInsecureHttpSet(methods: TeamBridgeMethods, allowed: boolean) { diff --git a/packages/core/src/team/bridge.ts b/packages/core/src/team/bridge.ts index a2e5874f48..42df915780 100644 --- a/packages/core/src/team/bridge.ts +++ b/packages/core/src/team/bridge.ts @@ -12,7 +12,11 @@ import type { HumanContext } from '../humans/context.js'; import type { BridgeResult } from '../bridge/method-utils.js'; import { TeamError, type TeamService } from './service.js'; -export function createTeamBridge(human: HumanContext, team: TeamService | undefined) { +export function createTeamBridge( + human: HumanContext, + team: TeamService | undefined, + currentOwnerDeviceId?: string, +) { const call = async ( run: (service: TeamService) => T | Promise, ): Promise> => { @@ -166,10 +170,17 @@ export function createTeamBridge(human: HumanContext, team: TeamService | undefi ), teamOwnerPasswordSet: (payload: unknown) => call((service) => { - const { password, current } = z - .object({ password: z.string().max(1024), current: z.string().max(1024).optional() }) + const { password, current, signOutOthers } = z + .object({ + password: z.string().max(1024), + current: z.string().max(1024).optional(), + signOutOthers: z.boolean().optional(), + }) .parse(payload); - return service.setOwnerPassword(human, password, current); + return service.setOwnerPassword(human, password, current, { + ...(signOutOthers === undefined ? {} : { signOutOthers }), + ...(currentOwnerDeviceId === undefined ? {} : { currentDeviceId: currentOwnerDeviceId }), + }); }), teamInsecureHttpSet: (payload: unknown) => call((service) => diff --git a/packages/core/src/team/http.ts b/packages/core/src/team/http.ts index c42831f43e..0a8c01f695 100644 --- a/packages/core/src/team/http.ts +++ b/packages/core/src/team/http.ts @@ -1,4 +1,5 @@ -import { createTeamDeviceHttp, type TeamDeviceHttp } from './device-http.js'; +import { createTeamDeviceHttp, deviceFailure, type TeamDeviceHttp } from './device-http.js'; +import { createTeamBridge } from './bridge.js'; import type { MemberDevices } from './devices.js'; import { isIPv4 } from 'node:net'; import { randomBytes } from 'node:crypto'; @@ -13,16 +14,17 @@ import { TeamError, type TeamService } from './service.js'; export const TEAM_PATH = '/botharness-device/team'; export const MEMBER_COOKIE = 'botharness-member'; +const rpcCallSchema = z.object({ + type: z.literal('client-request'), + rpcId: z.string(), + method: z.string(), + payload: z.object({ args: z.record(z.string(), z.unknown()).optional() }).optional(), +}); const rpcSchema = z.discriminatedUnion('op', [ z.object({ op: z.literal('call'), path: z.string(), - body: z.object({ - type: z.literal('client-request'), - rpcId: z.string(), - method: z.string(), - payload: z.object({ args: z.record(z.string(), z.unknown()).optional() }).optional(), - }), + body: rpcCallSchema, }), z.object({ op: z.literal('stream-open'), @@ -36,6 +38,11 @@ const rpcSchema = z.discriminatedUnion('op', [ export interface TeamHttp { handle(request: IncomingMessage, response: ServerResponse): Promise; + ownerDevicePassword( + request: IncomingMessage, + response: ServerResponse, + deviceId: string, + ): Promise; close(): Promise; device?: TeamDeviceHttp | undefined; } @@ -280,6 +287,22 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp { return { ...(device ? { device } : {}), + async ownerDevicePassword(request, response, deviceId) { + try { + const command = rpcCallSchema.parse(await readTeamBody(request)); + if (request.method !== 'POST' || command.method !== 'botharness/teamOwnerPasswordSet') + throw new TeamError('invalid-input'); + const currentOwner = options.team.ownerContext(); + const result = await createTeamBridge( + currentOwner, + options.team, + deviceId, + ).teamOwnerPasswordSet(command.payload?.args ?? {}); + teamJson(response, 200, { type: 'server-response', rpcId: command.rpcId, result }); + } catch (error) { + deviceFailure(response, error); + } + }, async handle(request, response) { const url = new URL(request.url ?? '/', 'http://member.invalid'); const path = url.pathname; diff --git a/packages/core/src/team/member-auth.ts b/packages/core/src/team/member-auth.ts index b2eb5c1a93..144c3014ec 100644 --- a/packages/core/src/team/member-auth.ts +++ b/packages/core/src/team/member-auth.ts @@ -133,6 +133,74 @@ function ownerPasswordEnabled(db: MemberAuthHost['db']): boolean { ); } +export async function setOwnerPassword( + this: MemberAuthHost, + human: HumanContext, + password: string, + current?: string, + options?: { signOutOthers?: boolean; currentDeviceId?: string }, +): Promise { + this.owner(human); + const previous = this.credential(human.humanId); + if (previous && !(await verifyPassword(current ?? '', previous.hash))) + throw new TeamError('credentials-invalid'); + this.owner(human); + if (!strongPassword(password)) throw new TeamError('password-weak'); + const hash = await hashPassword(password); + this.owner(human); + if (this.credential(human.humanId)?.hash.hash !== previous?.hash.hash) + throw new TeamError('credentials-invalid'); + + const currentDeviceId = options?.currentDeviceId; + if ( + currentDeviceId !== undefined && + !this.db.read((db) => + db + .prepare(`SELECT 1 FROM paired_devices WHERE device_id = ? AND human_id = ? + AND enrollment = 'owner-password' AND revoked_at IS NULL`) + .get(currentDeviceId, human.humanId), + ) + ) + throw new TeamError('device-revoked'); + + const others = + previous && options?.signOutOthers + ? this.db.read((db) => + z.array(z.object({ device_id: z.string() })).parse( + db + .prepare(`SELECT device_id FROM paired_devices WHERE human_id = ? + AND enrollment = 'owner-password' AND revoked_at IS NULL AND device_id <> ?`) + .all(human.humanId, currentDeviceId ?? ''), + ), + ) + : []; + const pairing = this.pairing; + if (others.length > 0 && !pairing) throw new TeamError('unavailable'); + + this.db.transaction( + (db) => { + if (previous) + db.prepare( + 'UPDATE member_credentials SET password_json = ?, must_change = 0 WHERE human_id = ?', + ).run(credentialPasswordJson(hash, human.humanId), human.humanId); + else + db.prepare("INSERT INTO member_credentials VALUES (?, 'owner', ?, '[]', 0)").run( + human.humanId, + credentialPasswordJson(hash, human.humanId), + ); + if (others.length > 0) { + const revoke = db.prepare('UPDATE paired_devices SET revoked_at = ? WHERE device_id = ?'); + const revokedAt = new Date(this.now()).toISOString(); + for (const { device_id } of others) revoke.run(revokedAt, device_id); + } + }, + others.length > 0 ? ['team', 'paired-devices'] : ['team'], + ); + for (const { device_id } of others) pairing?.revoke(device_id); + this.invalidate(); + this.log('owner-password-updated', { initiator: 'owner', revokedDevices: others.length }); +} + export function ownerPasswordSignIn( this: MemberAuthHost, human: HumanContext, diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts index 707800f876..32eb04fcc3 100644 --- a/packages/core/src/team/service.ts +++ b/packages/core/src/team/service.ts @@ -27,7 +27,7 @@ import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol'; import type { OperationalDatabaseModulePort } from '../database/owner.js'; import { humanContext, type HumanContext } from '../humans/context.js'; import type { ChannelStore } from '../channels/store.js'; -import { hashPassword, passwordHashSchema, strongPassword, verifyPassword } from './password.js'; +import { hashPassword, passwordHashSchema, verifyPassword } from './password.js'; import { SignInRateLimit } from './rate-limit.js'; import { memberUrls } from './member-urls.js'; @@ -618,32 +618,15 @@ export class TeamService { human: HumanContext, password: string, current?: string, + options?: Parameters[3], ): Promise { - this.owner(human); - const previous = this.credential(human.humanId); - if (previous && !(await verifyPassword(current ?? '', previous.hash))) - throw new TeamError('credentials-invalid'); - this.owner(human); - if (!strongPassword(password)) throw new TeamError('password-weak'); - const hash = await hashPassword(password); - this.owner(human); - if (this.credential(human.humanId)?.hash.hash !== previous?.hash.hash) - throw new TeamError('credentials-invalid'); - this.db.transaction( - (db) => { - if (previous) - db.prepare( - 'UPDATE member_credentials SET password_json = ?, must_change = 0 WHERE human_id = ?', - ).run(credentialPasswordJson(hash, human.humanId), human.humanId); - else - db.prepare("INSERT INTO member_credentials VALUES (?, 'owner', ?, '[]', 0)").run( - human.humanId, - credentialPasswordJson(hash, human.humanId), - ); - }, - ['team'], + await memberAuth.setOwnerPassword.call( + this.#memberOperations, + human, + password, + current, + options, ); - this.invalidate(); return this.mode(human); } diff --git a/packages/core/test/cli-team.test.ts b/packages/core/test/cli-team.test.ts index 13c2d0db5a..749deefb10 100644 --- a/packages/core/test/cli-team.test.ts +++ b/packages/core/test/cli-team.test.ts @@ -525,6 +525,28 @@ describe('Team CLI', () => { ]); }); + it('passes the Owner device sign-out choice only with explicit CLI confirmation', async () => { + const f = await host(); + const args = ['team-mode', 'owner-password', '--password-stdin', '--sign-out-others=true']; + const input = '{"current":"previous-owner-password","password":"updated-owner-password"}'; + const refused = await run(f.url, args, input); + expect(refused.output).toMatchObject({ error: { code: 'confirm-required' } }); + expect(f.calls).toEqual([]); + + const changed = await run(f.url, [...args, '--confirm'], input); + expect(changed.status).toBe(0); + expect(changed.text + changed.errorText).not.toContain('updated-owner-password'); + expect(f.calls[0]?.input).toMatchObject({ + payload: { + args: { + current: 'previous-owner-password', + password: 'updated-owner-password', + signOutOthers: true, + }, + }, + }); + }); + it('reads Owner and member passwords only from stdin and requires confirmation for insecure HTTP', async () => { const f = await host(); expect( diff --git a/packages/core/test/owner-password-device-sign-in.test.ts b/packages/core/test/owner-password-device-sign-in.test.ts index 476c52fe6e..fc64b40b2a 100644 --- a/packages/core/test/owner-password-device-sign-in.test.ts +++ b/packages/core/test/owner-password-device-sign-in.test.ts @@ -152,6 +152,101 @@ it('reuses an existing Owner credential and keeps standalone configuration Owner }); }); +it.each([true, false])( + 'changes the Owner password while respecting sign-out choice %s', + async (signOutOthers) => { + const f = teamFixture(); + f.team.bindPairing(f.pairing); + const host = await memberDeviceHost(f); + const next = 'new-standalone-owner-password'; + expect( + await f.methods(owner).ownerPasswordSignInSet({ + enabled: true, + username: 'my-owner', + password, + }), + ).toMatchObject({ ok: true }); + + const admit = async () => { + const encryption = deviceEncryption(f); + const { value } = z + .object({ + ok: z.literal(true), + value: z.object({ credential: z.string(), deviceId: z.string() }), + }) + .parse(await signIn(f, host, encryption)); + return { + ...value, + carrier: encryptedCarrier({ + credential: value.credential, + encryption: { ...encryption, required: true }, + hostId: f.pairing.host().id, + raw: host.carrier, + }), + }; + }; + const current = await admit(); + const other = await admit(); + const qr = f.pairing.redeem({ offer: f.pairing.createOffer().offer }); + if (!qr.ok) throw new Error(qr.code); + const feed = (device: typeof current) => + device.carrier.request(target + '/botharness-device/feed-read', { + method: 'POST', + signal: AbortSignal.timeout(5_000), + }); + try { + expect((await feed(current)).status).toBe(200); + expect((await feed(other)).status).toBe(200); + + const method = 'botharness/teamOwnerPasswordSet'; + const changed = await current.carrier.request(target + `/botharness-device/api/${method}`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', + rpcId: 'owner-password-change', + method, + payload: { + args: { + password: next, + current: password, + signOutOthers, + currentDeviceId: other.deviceId, + }, + }, + }), + signal: AbortSignal.timeout(5_000), + }); + expect(JSON.parse(await changed.text())).toMatchObject({ + type: 'server-response', + rpcId: 'owner-password-change', + result: { ok: true }, + }); + expect((await feed(current)).status).toBe(200); + if (signOutOthers) { + await expect(feed(other)).rejects.toThrow(); + expect(f.pairing.check(other.deviceId)).toMatchObject({ + ok: false, + code: 'device-revoked', + }); + } else { + expect((await feed(other)).status).toBe(200); + } + expect((await host.post('/feed-read', {}, qr.credential)).status).toBe(200); + expect(await signIn(f, host, deviceEncryption(f))).toMatchObject({ + ok: false, + code: 'credentials-invalid', + }); + expect(await signIn(f, host, deviceEncryption(f), { attempt: next })).toMatchObject({ + ok: true, + }); + } finally { + current.carrier.close?.(); + other.carrier.close?.(); + } + }, +); + it('uses the same failure and account/source limits for missing and wrong Owner credentials', async () => { const f = teamFixture(); await f.methods(owner).ownerPasswordSignInSet({ enabled: true, username: 'my-owner', password }); From e94a9b06b4acb3bac290cfa8ae773afa83686b9d Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 06:00:51 +0900 Subject: [PATCH 08/16] Map remote Owner password settings to the CLI Issue: #4899 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- scripts/cli-ui-inventory.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/cli-ui-inventory.json b/scripts/cli-ui-inventory.json index fef1f15280..88eda2811e 100644 --- a/scripts/cli-ui-inventory.json +++ b/scripts/cli-ui-inventory.json @@ -1244,6 +1244,7 @@ "setting:packages/client/src/client/team-settings.tsx:{t('team.members.title')}", "setting:packages/client/src/client/team-settings.tsx:{t('team.mode.title')}", "setting:packages/client/src/client/team-settings.tsx:{t('team.ownerPassword.title')}", + "setting:packages/client/src/client/settings-environment.tsx:{t('team.ownerPassword.title')}", "setting:packages/client/src/client/team-settings.tsx:{view.viewer.displayName}", "setting:packages/client/src/client/channel-access-settings.tsx:{t('channelAccess.admins')}", "setting:packages/client/src/client/channel-access-settings.tsx:{t('channelAccess.visibility')}", From 0f2fbf9d124e89f8cbcb03c479fc5e00ef376cf5 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 08:21:13 +0900 Subject: [PATCH 09/16] Close Owner sign-in review gaps Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- docs/architecture/botharness-architecture.md | 2 +- docs/decisions/connections.md | 2 ++ .../environments/connections-locale.ts | 2 +- .../core/src/devices/encrypted-gateway.ts | 4 +-- .../owner-password-device-sign-in.test.ts | 27 +++++++++++++- packages/host-client/src/client-resources.ts | 6 ++-- packages/host-client/src/client.ts | 6 ++-- .../host-client/test/owner-sign-in.test.ts | 36 +++++++++++++++++-- packages/host-protocol/src/route.ts | 10 ++++++ 9 files changed, 81 insertions(+), 14 deletions(-) diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md index ed0c83a1fa..a58e6ee963 100644 --- a/docs/architecture/botharness-architecture.md +++ b/docs/architecture/botharness-architecture.md @@ -1583,7 +1583,7 @@ Managed Tailscale publishing belongs to the same device-access Plugin lifecycle. The cloudflared-only origin accepts `/botharness-device/channel` and refuses legacy application HTTP, stream tickets and WebView paths. The shared phone/browser Host client carries unary RPCs, logical `remote.mux`, uploads, downloads, avatars, private input and push registration inside ciphertext. The encrypted adapter forwards to the existing Device Gateway on loopback; native DSH Typert/API Gateway remains the sole dispatcher. Loopback/Tailscale retain their contract. Legacy Connect pairings without pins fail closed and must be paired again; no failure clears a pin or retries plaintext through Connect. -Native private input uses masked fields and the existing credential owner; values stay outside chat drafts, messages and telemetry. The phone's full Host WebView remains removed on every route. Browser/Computer viewers are explicitly unavailable on Connect pending their own media/signaling qualification; the Host and Tailscale remain available. The browser requires independently trusted serving code and origin-local key storage; it does not claim hardware protection. +Native private input uses masked fields and the existing credential owner; values stay outside chat drafts, messages and telemetry. The phone's full Host WebView remains removed on every route. Browser and Computer viewers are available through direct Host access and QR-paired Tailscale. Connect and password-enrolled Tailscale use the encrypted device channel, where viewers require separate media and signaling qualification. The browser requires independently trusted serving code and origin-local key storage; it does not claim hardware protection. [ADR-0244](../decisions/connections.md#adr-0244) is approved. Its implementation, protocol vectors, runtime evidence, native acceptance, independent security review and deployment are separate gates; a green source test is not proof of a real phone through Cloudflare. The [Track A audit](../research/2026-10-22-connect-secret-safety-audit.md) remains historical evidence for the interim refusal. diff --git a/docs/decisions/connections.md b/docs/decisions/connections.md index 0b80e5958c..5f471ebf0d 100644 --- a/docs/decisions/connections.md +++ b/docs/decisions/connections.md @@ -77,6 +77,8 @@ The Client and Host complete their authenticated Noise channel before exchanging After authentication, the Host enrolls the exact Client device key with a revocable grant for that Human. The current Host Owner receives the same authority as an Owner-paired device. A Team member receives a member grant and completes any required first-password change before normal access. The Host records how it issued the device grant so the Host Owner can revoke password-enrolled Owner devices together when changing the password. See [Host password policy](team-mode.md#host-password-sign-in-and-team-mode). +Password-enrolled Owner devices keep the Noise requirement on HTTPS, including Tailscale. Browser and Computer viewers need their own media and signaling support on the encrypted device channel. They remain available through direct Host access and the existing QR-paired Tailscale path. + Why. The URL controls how a Client reaches the Host. The authenticated Host key controls which Host receives the password. This supports HTTP-only LANs and TLS-terminating relays with the same credential protection. Enforced by the [Remote Hosts verification journey](../../.agents/skills/verify-deepseekbot/features/remote-hosts.md#standalone-owner-password-sign-in-4898) and the remaining acceptance cases in [#4896](https://github.com/BotHarness/DeepSeekBot/issues/4896). diff --git a/packages/client/src/client/features/environments/connections-locale.ts b/packages/client/src/client/features/environments/connections-locale.ts index 41be800f22..36c7b90260 100644 --- a/packages/client/src/client/features/environments/connections-locale.ts +++ b/packages/client/src/client/features/environments/connections-locale.ts @@ -564,7 +564,7 @@ export const en = { 'connections.ownerSignIn.setupTitle': 'Turn on password sign-in', 'connections.ownerSignIn.username': 'Username: {username}', 'connections.ownerSignIn.usernameRule': - 'Use 2–32 characters. Start with a lowercase letter or number, then use letters, numbers, dots, dashes, or underscores.', + 'Use 2–32 lowercase letters, numbers, dots, dashes, or underscores. Start with a letter or number.', 'connections.ownerSignIn.passwordTooLong': 'Use a shorter password.', 'connections.ownerSignIn.disableHint': 'Connected devices keep access when turned off.', 'connections.ownerSignIn.loadFailed': 'Could not load. Try again.', diff --git a/packages/core/src/devices/encrypted-gateway.ts b/packages/core/src/devices/encrypted-gateway.ts index f51b14aba2..1cbee81bcf 100644 --- a/packages/core/src/devices/encrypted-gateway.ts +++ b/packages/core/src/devices/encrypted-gateway.ts @@ -655,8 +655,8 @@ export function createEncryptedGateway(options: { const result = ownerSignIn ? await options.memberDevices.signInOwner(input['input'], remoteAddress, publicKey) : await options.memberDevices.signIn(input['input'], remoteAddress, publicKey); - if (!closed) send({ type: reply, result: { ok: true, value: result } }); - else if (ownerSignIn) options.pairing.revoke(result.deviceId); + const sent = send({ type: reply, result: { ok: true, value: result } }); + if (!sent && ownerSignIn) options.pairing.revoke(result.deviceId); } catch (error) { if (!closed) send({ diff --git a/packages/core/test/owner-password-device-sign-in.test.ts b/packages/core/test/owner-password-device-sign-in.test.ts index 476c52fe6e..7c60c84321 100644 --- a/packages/core/test/owner-password-device-sign-in.test.ts +++ b/packages/core/test/owner-password-device-sign-in.test.ts @@ -1,7 +1,8 @@ import { randomBytes } from 'node:crypto'; import { encryptedCarrier, openNoiseSocket } from '@botharness/host-client/encrypted-carrier'; import { Peer } from '@deepseek-ai/dsh-client-connection'; -import { afterEach, expect, it } from 'vitest'; +import { afterEach, expect, it, vi } from 'vitest'; +import { WebSocket } from 'ws'; import { z } from 'zod'; import { OWNER_HUMAN_CONTEXT as owner, humanContext } from '../src/humans/context.js'; import { cleanup, memberDeviceHost, teamFixture } from './team-mode-fixtures.js'; @@ -125,6 +126,30 @@ it('enrolls an Owner device through Noise with Team mode off and revokes its adm } }); +it('revokes the new Owner device when the encrypted reply cannot be sent', async () => { + const f = teamFixture(); + await f.methods(owner).ownerPasswordSignInSet({ enabled: true, username: 'my-owner', password }); + const host = await memberDeviceHost(f); + const send = vi.spyOn(WebSocket.prototype, 'send'); + const signInOwner = f.devices.signInOwner.bind(f.devices); + const enroll = vi.spyOn(f.devices, 'signInOwner').mockImplementationOnce(async (...args) => { + const result = await signInOwner(...args); + send.mockImplementationOnce(() => { + throw new Error('socket send failed'); + }); + return result; + }); + try { + await expect(signIn(f, host, deviceEncryption(f))).rejects.toThrow(); + expect(f.pairing.list()).toMatchObject([ + { enrollment: 'owner-password', revokedAt: expect.any(String) }, + ]); + } finally { + enroll.mockRestore(); + send.mockRestore(); + } +}); + it('reuses an existing Owner credential and keeps standalone configuration Owner-only', async () => { const f = teamFixture(); await f.team.setOwnerPassword(owner, password); diff --git a/packages/host-client/src/client-resources.ts b/packages/host-client/src/client-resources.ts index 39eb1a24eb..62b4be273c 100644 --- a/packages/host-client/src/client-resources.ts +++ b/packages/host-client/src/client-resources.ts @@ -1,5 +1,5 @@ import type { HostCarrier } from '@botharness/host-protocol/carrier'; -import { checkRoute, isEncryptedRoute } from '@botharness/host-protocol/route'; +import { isDeviceRoute, isEncryptedRoute } from '@botharness/host-protocol/route'; import type { HostClientOptions, RemoteSource } from './client-contract'; import { encodeBase64 } from './encrypted-carrier'; import { DEVICE_PREFIX } from './pairing'; @@ -21,7 +21,7 @@ export function createHostResources( const scope = options.hostId ? { scope: options.hostId } : {}; const resource = (path: string): RemoteSource => { if ( - checkRoute(connection.route, options.encryption?.privateRelay).ok && + isDeviceRoute(connection.route, options.encryption) && !isEncryptedRoute(connection.route, options.encryption) ) return { uri: absolute(path), headers: authorization, ...scope }; @@ -46,7 +46,7 @@ export function createHostResources( }; }; const avatar = (path: string): { avatarUrl?: string; avatarHeaders?: Record } => { - if (!checkRoute(connection.route, options.encryption?.privateRelay).ok) return {}; + if (!isDeviceRoute(connection.route, options.encryption)) return {}; if (!isEncryptedRoute(connection.route, options.encryption)) return { avatarUrl: absolute(path), avatarHeaders: authorization }; const key = connection.route + path; diff --git a/packages/host-client/src/client.ts b/packages/host-client/src/client.ts index 45b41799bf..e5dc5d78d4 100644 --- a/packages/host-client/src/client.ts +++ b/packages/host-client/src/client.ts @@ -1,9 +1,8 @@ import type { HostSocket } from '@botharness/host-protocol/carrier'; import { - checkRoute, isConnectRoute, + isDeviceRoute, isEncryptedRoute, - isHttpsOrigin, isLanRoute, socketOrigin, } from '@botharness/host-protocol/route'; @@ -956,8 +955,7 @@ export function createHostClient(options: HostClientOptions): HostClient { }, resource: resources.resource, secretInputAllowed: () => - (checkRoute(route, options.encryption?.privateRelay).ok || - (options.encryption?.required === true && isHttpsOrigin(route))) && + isDeviceRoute(route, options.encryption) && (!isEncryptedRoute(route, options.encryption) || options.encryption !== undefined), onLive(listener) { liveListeners.add(listener); diff --git a/packages/host-client/test/owner-sign-in.test.ts b/packages/host-client/test/owner-sign-in.test.ts index 695dab5e53..74b30a5ec6 100644 --- a/packages/host-client/test/owner-sign-in.test.ts +++ b/packages/host-client/test/owner-sign-in.test.ts @@ -4,6 +4,7 @@ import type { HostCarrier, HostRequest, HostSocketEvents } from '@botharness/hos import { ConnectChannel } from '@botharness/host-protocol/noise/channel'; import { noiseFingerprint, noisePublicKey } from '@botharness/host-protocol/noise/xk'; import { teamRecord } from '@botharness/host-protocol/team-invitation'; +import { createHostResources } from '../src/client-resources'; import { encryptedCarrier } from '../src/encrypted-carrier'; import { parseSavedHost, serializeSavedHost } from '../src/hosts'; import { signInOwnerDevice } from '../src/owner-sign-in'; @@ -12,6 +13,7 @@ const route = 'https://studio.example'; const password = 'test-only-sign-in-password'; const deviceId = 'test-device-1234'; const credential = deviceId + '.' + 'a'.repeat(43); +const avatarPath = '/api/bots/avatar'; function host({ differentSocketKey = false } = {}) { const privateKey = randomBytes(32); @@ -54,13 +56,16 @@ function host({ differentSocketKey = false } = {}) { }); if (message['type'] === 'admit' && message['credential'] === credential) send({ type: 'admitted' }); - if (message['type'] === 'request') + if (message['type'] === 'request') { + const avatar = message['path'] === '/botharness-device' + avatarPath; send({ type: 'response', id: message['id'], status: 200, - body: btoa('{"bots":[]}'), + ...(avatar ? { contentType: 'image/png' } : {}), + body: btoa(avatar ? 'test-avatar' : '{"bots":[]}'), }); + } } } catch { events.closed('channel-handshake-rejected'); @@ -179,6 +184,33 @@ describe('Owner password sign-in', () => { } }); + it('loads a Host avatar through Noise on a password-enrolled custom HTTPS origin', async () => { + const test = host(); + const signed = await signInOwnerDevice(test.input); + if (!signed.ok) throw new Error(signed.code); + const transport = encryptedCarrier({ ...signed.value, raw: test.carrier }); + const resources = createHostResources( + { ...signed.value, carrier: test.carrier }, + transport, + { authorization: `Device ${credential}` }, + 3000, + { route, running: true }, + () => {}, + ); + try { + expect(resources.avatar(avatarPath)).toEqual({}); + await vi.waitFor(() => + expect(resources.avatar(avatarPath)).toEqual({ + avatarUrl: `data:image/png;base64,${btoa('test-avatar')}`, + avatarHeaders: {}, + }), + ); + expect(test.request).toHaveBeenCalledOnce(); + } finally { + transport.close?.(); + } + }); + it('does not use HTTP or continue after HTTPS discovery rejects', async () => { const test = host(); expect(await signInOwnerDevice({ ...test.input, route: 'http://studio.example' })).toEqual({ diff --git a/packages/host-protocol/src/route.ts b/packages/host-protocol/src/route.ts index 0b094802c9..57a2dc9cac 100644 --- a/packages/host-protocol/src/route.ts +++ b/packages/host-protocol/src/route.ts @@ -78,6 +78,16 @@ export function isHttpsOrigin(input: string): boolean { } } +export function isDeviceRoute( + route: string, + encryption?: { privateRelay?: PrivateOrigins; required?: true }, +): boolean { + return ( + checkRoute(route, encryption?.privateRelay).ok || + (encryption?.required === true && isHttpsOrigin(route)) + ); +} + export function isConnectRoute(route: string): boolean { try { return CONNECT_HOSTNAME.test(new URL(route).hostname); From 70bfc1d82cbd8c9b96c49440693c920f2efce2bf Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 08:41:32 +0900 Subject: [PATCH 10/16] Share Owner credential writes across settings Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- .../client/src/client/features/team/locale.ts | 4 +- .../client/test/team-invitation-text.test.ts | 11 ++- packages/core/src/team/member-auth.ts | 76 ++++++++++++++----- packages/core/src/team/service.ts | 32 ++------ .../owner-password-device-sign-in.test.ts | 32 ++++++++ 5 files changed, 102 insertions(+), 53 deletions(-) diff --git a/packages/client/src/client/features/team/locale.ts b/packages/client/src/client/features/team/locale.ts index 0440581ae0..a2da5df176 100644 --- a/packages/client/src/client/features/team/locale.ts +++ b/packages/client/src/client/features/team/locale.ts @@ -97,7 +97,7 @@ export const zh = { 'team.invite.text.intro': '你被邀请加入 {host} 的 Team。', 'team.invite.text.phone': '手机:在 Tobs 里打开这个邀请链接(10 分钟内有效):{link}', 'team.invite.text.desktop': - '电脑:在 Tobs「环境」里点「添加远程」→「以团队成员身份登录」,地址填 {address}', + '桌面端:在 Tobs「环境」里点「添加远程」→「以团队成员身份登录」,地址填 {address}', 'team.invite.text.username': '用户名:{username}', 'team.invite.text.password': '一次性密码:{password}(第一次登录后改成你自己的密码)', 'team.invite.text.fingerprint': '登录时核对 Host 指纹:{fingerprint}', @@ -499,7 +499,7 @@ export const en = { 'team.invite.text.phone': 'Phone: open this invitation link in Tobs (valid for 10 minutes): {link}', 'team.invite.text.desktop': - 'Computer: in Tobs Environments, choose Add remote → Sign in as a team member, and enter {address}', + 'Desktop: in Tobs Environments, choose Add remote → Sign in as a team member, and enter {address}', 'team.invite.text.username': 'Username: {username}', 'team.invite.text.password': 'One-time password: {password} (you choose your own password after the first sign-in)', diff --git a/packages/client/test/team-invitation-text.test.ts b/packages/client/test/team-invitation-text.test.ts index abf5427034..575ba0a1f3 100644 --- a/packages/client/test/team-invitation-text.test.ts +++ b/packages/client/test/team-invitation-text.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { zhTranslate } from '../src/client/locale.js'; +import { en, zhTranslate } from '../src/client/locale.js'; import { invitationText, loadMemberInvitation } from '../src/client/team-invitation-text.js'; const fingerprint = 'ab'.repeat(32); @@ -14,7 +14,7 @@ const link = `deepseekbot://team?i=${Buffer.from( ).toString('base64url')}`; describe('invitationText', () => { - it('gives the phone link, the computer address, username, one-time password and fingerprint', () => { + it('gives the phone link, the desktop address, username, one-time password and fingerprint', () => { const text = invitationText(zhTranslate, { link, username: 'erin', @@ -23,7 +23,12 @@ describe('invitationText', () => { }); expect(text).toContain('Studio'); expect(text).toContain(link); - expect(text).toContain('https://studio.tail.ts.net/'); + expect(text).toContain( + '桌面端:在 Tobs「环境」里点「添加远程」→「以团队成员身份登录」,地址填 https://studio.tail.ts.net/', + ); + expect(en['team.invite.text.desktop']).toBe( + 'Desktop: in Tobs Environments, choose Add remote → Sign in as a team member, and enter {address}', + ); expect(text).toContain('erin'); expect(text).toContain('one-time-secret'); expect(text).toContain(fingerprint); diff --git a/packages/core/src/team/member-auth.ts b/packages/core/src/team/member-auth.ts index b2eb5c1a93..7ac3bf543c 100644 --- a/packages/core/src/team/member-auth.ts +++ b/packages/core/src/team/member-auth.ts @@ -56,7 +56,6 @@ export type MemberAuthHost = { deviceGrantResult: TeamService['deviceGrantResult']; ensureTob: TeamService['ensureTob']; invalidate: TeamService['invalidate']; - hasCredential: TeamService['hasCredential']; isOwner: TeamService['isOwner']; limiter: TeamService['limiter']; log: TeamService['log']; @@ -133,6 +132,59 @@ function ownerPasswordEnabled(db: MemberAuthHost['db']): boolean { ); } +export async function setOwnerPassword( + this: MemberAuthHost, + human: HumanContext, + password: string, + options: + | { kind: 'settings'; current: string | undefined } + | { kind: 'enable-sign-in'; username: string }, +): Promise { + this.owner(human); + const previous = this.credential(human.humanId); + const username = options.kind === 'enable-sign-in' ? options.username : 'owner'; + if (options.kind === 'enable-sign-in') { + if (previous) throw new TeamError('invalid-input'); + if (!/^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username)) throw new TeamError('username-invalid'); + } else if (previous) { + if (!(await verifyPassword(options.current ?? '', previous.hash))) + throw new TeamError('credentials-invalid'); + this.owner(human); + } + if (!strongPassword(password)) throw new TeamError('password-weak'); + if (options.kind === 'enable-sign-in' && this.byUsername(username)) + throw new TeamError('username-taken'); + + const hash = await hashPassword(password); + this.owner(human); + if (this.credential(human.humanId)?.hash.hash !== previous?.hash.hash) + throw new TeamError( + options.kind === 'enable-sign-in' ? 'invalid-input' : 'credentials-invalid', + ); + if (options.kind === 'enable-sign-in' && this.byUsername(username)) + throw new TeamError('username-taken'); + + const credential = credentialPasswordJson(hash, human.humanId); + this.db.transaction( + (db) => { + if (previous) + db.prepare( + 'UPDATE member_credentials SET password_json = ?, must_change = 0 WHERE human_id = ?', + ).run(credential, human.humanId); + else + db.prepare("INSERT INTO member_credentials VALUES (?, ?, ?, '[]', 0)").run( + human.humanId, + username, + credential, + ); + if (options.kind === 'enable-sign-in') + db.prepare('UPDATE team_settings SET owner_password_sign_in = 1 WHERE singleton = 1').run(); + }, + ['team'], + ); + this.invalidate(); +} + export function ownerPasswordSignIn( this: MemberAuthHost, human: HumanContext, @@ -155,25 +207,7 @@ export async function ownerPasswordSignInSet( if (enabled && previous.username === undefined) { if (username === undefined || password === undefined) throw new TeamError('owner-password-required'); - if (!/^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username)) throw new TeamError('username-invalid'); - if (!strongPassword(password)) throw new TeamError('password-weak'); - if (this.byUsername(username)) throw new TeamError('username-taken'); - const hash = await hashPassword(password); - this.owner(human); - if (this.hasCredential(human.humanId)) throw new TeamError('invalid-input'); - if (this.byUsername(username)) throw new TeamError('username-taken'); - this.db.transaction( - (db) => { - db.prepare('INSERT INTO member_credentials VALUES (?, ?, ?, ?, 0)').run( - human.humanId, - username, - credentialPasswordJson(hash, human.humanId), - '[]', - ); - db.prepare('UPDATE team_settings SET owner_password_sign_in = 1 WHERE singleton = 1').run(); - }, - ['team'], - ); + await setOwnerPassword.call(this, human, password, { kind: 'enable-sign-in', username }); } else { if (username !== undefined || password !== undefined) throw new TeamError('invalid-input'); if (previous.enabled === enabled) return previous; @@ -184,8 +218,8 @@ export async function ownerPasswordSignInSet( .run(Number(enabled)), ['team'], ); + this.invalidate(); } - this.invalidate(); this.log('owner-password-sign-in-changed', { initiator: 'owner', enabled }); return ownerPasswordSignIn.call(this, human); } diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts index 707800f876..e721d58a7e 100644 --- a/packages/core/src/team/service.ts +++ b/packages/core/src/team/service.ts @@ -27,7 +27,7 @@ import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol'; import type { OperationalDatabaseModulePort } from '../database/owner.js'; import { humanContext, type HumanContext } from '../humans/context.js'; import type { ChannelStore } from '../channels/store.js'; -import { hashPassword, passwordHashSchema, strongPassword, verifyPassword } from './password.js'; +import { hashPassword, passwordHashSchema, verifyPassword } from './password.js'; import { SignInRateLimit } from './rate-limit.js'; import { memberUrls } from './member-urls.js'; @@ -218,7 +218,6 @@ export class TeamService { get ensureTob() { return service.ensureTob?.bind(service); }, - hasCredential: (...args) => service.hasCredential(...args), invalidate: (...args) => service.invalidate(...args), isOwner: (...args) => service.isOwner(...args), get limiter() { @@ -619,31 +618,10 @@ export class TeamService { password: string, current?: string, ): Promise { - this.owner(human); - const previous = this.credential(human.humanId); - if (previous && !(await verifyPassword(current ?? '', previous.hash))) - throw new TeamError('credentials-invalid'); - this.owner(human); - if (!strongPassword(password)) throw new TeamError('password-weak'); - const hash = await hashPassword(password); - this.owner(human); - if (this.credential(human.humanId)?.hash.hash !== previous?.hash.hash) - throw new TeamError('credentials-invalid'); - this.db.transaction( - (db) => { - if (previous) - db.prepare( - 'UPDATE member_credentials SET password_json = ?, must_change = 0 WHERE human_id = ?', - ).run(credentialPasswordJson(hash, human.humanId), human.humanId); - else - db.prepare("INSERT INTO member_credentials VALUES (?, 'owner', ?, '[]', 0)").run( - human.humanId, - credentialPasswordJson(hash, human.humanId), - ); - }, - ['team'], - ); - this.invalidate(); + await memberAuth.setOwnerPassword.call(this.#memberOperations, human, password, { + kind: 'settings', + current, + }); return this.mode(human); } diff --git a/packages/core/test/owner-password-device-sign-in.test.ts b/packages/core/test/owner-password-device-sign-in.test.ts index 7c60c84321..9f6116fe93 100644 --- a/packages/core/test/owner-password-device-sign-in.test.ts +++ b/packages/core/test/owner-password-device-sign-in.test.ts @@ -150,6 +150,38 @@ it('revokes the new Owner device when the encrypted reply cannot be sent', async } }); +it('commits only one credential when the Owner setup entry points race', async () => { + const f = teamFixture(); + const [standalone, team] = await Promise.allSettled([ + f.team.ownerPasswordSignInSet(owner, { enabled: true, username: 'my-owner', password }), + f.team.setOwnerPassword(owner, 'legacy-owner-password-1'), + ]); + if (standalone.status === 'fulfilled') { + expect(team).toMatchObject({ status: 'rejected', reason: { code: 'credentials-invalid' } }); + expect(f.team.ownerPasswordSignIn(owner)).toEqual({ enabled: true, username: 'my-owner' }); + } else { + expect(standalone.reason).toMatchObject({ code: 'invalid-input' }); + expect(team.status).toBe('fulfilled'); + expect(f.team.ownerPasswordSignIn(owner)).toEqual({ enabled: false, username: 'owner' }); + } +}); + +it('preserves the chosen username and standalone switch when Team settings updates the password', async () => { + const f = teamFixture(); + await f.team.ownerPasswordSignInSet(owner, { enabled: true, username: 'my-owner', password }); + const next = 'replacement-owner-password-1'; + await f.team.setOwnerPassword(owner, next, password); + expect(f.team.ownerPasswordSignIn(owner)).toEqual({ enabled: true, username: 'my-owner' }); + const host = await memberDeviceHost(f); + await expect(signIn(f, host, deviceEncryption(f), { attempt: next })).resolves.toMatchObject({ + ok: true, + }); + await expect(signIn(f, host, deviceEncryption(f))).resolves.toEqual({ + ok: false, + code: 'credentials-invalid', + }); +}); + it('reuses an existing Owner credential and keeps standalone configuration Owner-only', async () => { const f = teamFixture(); await f.team.setOwnerPassword(owner, password); From 552bc0398cb7a650771cefcd51d86c689626e5a1 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 08:50:55 +0900 Subject: [PATCH 11/16] Share Host discovery across password sign-in flows Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- .../features/remote-hosts.md | 1 + .../verify-deepseekbot/features/team-mode.md | 1 + packages/host-client/src/owner-sign-in.ts | 31 +++----- packages/host-client/src/sign-in-discovery.ts | 70 +++++++++++++++++++ packages/host-client/src/team-client.ts | 26 +++---- packages/host-client/src/team-sign-in.ts | 33 ++------- .../host-client/test/owner-sign-in.test.ts | 17 +++++ .../host-client/test/team-sign-in.test.ts | 50 ++++++++++++- 8 files changed, 158 insertions(+), 71 deletions(-) create mode 100644 packages/host-client/src/sign-in-discovery.ts diff --git a/.agents/skills/verify-deepseekbot/features/remote-hosts.md b/.agents/skills/verify-deepseekbot/features/remote-hosts.md index cd90de78d8..c2c28d1bd7 100644 --- a/.agents/skills/verify-deepseekbot/features/remote-hosts.md +++ b/.agents/skills/verify-deepseekbot/features/remote-hosts.md @@ -6,6 +6,7 @@ The browser reads each Remote Host Feed through its own Paired Device and the sh - `packages/client/src/client/remote-host*.{ts,tsx}` - `packages/client/src/client/features/environments/remote-host-*.ts` +- `packages/host-client/src/{owner-sign-in,sign-in-discovery}.ts` - `packages/client/src/client/relationship{s,-settings}.{ts,tsx}` - `packages/core/src/devices/relationship*.ts` diff --git a/.agents/skills/verify-deepseekbot/features/team-mode.md b/.agents/skills/verify-deepseekbot/features/team-mode.md index 3de6144dc9..741fb8117f 100644 --- a/.agents/skills/verify-deepseekbot/features/team-mode.md +++ b/.agents/skills/verify-deepseekbot/features/team-mode.md @@ -6,6 +6,7 @@ - `packages/core/src/team/**` - `packages/client/src/client/team-*` - `packages/host-client/src/team-*.ts` +- `packages/host-client/src/sign-in-discovery.ts` - `packages/host-client/src/shared/team-sign-in-page.ts` - `apps/mobile/src/team/**` - `packages/core/src/features/team/{methods,rpc}.ts` diff --git a/packages/host-client/src/owner-sign-in.ts b/packages/host-client/src/owner-sign-in.ts index d4722b73d9..3607d8335c 100644 --- a/packages/host-client/src/owner-sign-in.ts +++ b/packages/host-client/src/owner-sign-in.ts @@ -1,15 +1,14 @@ import type { HostCarrier } from '@botharness/host-protocol/carrier'; -import { CONNECT_CHANNEL_PATH } from '@botharness/host-protocol/noise/channel'; -import { noiseFingerprint } from '@botharness/host-protocol/noise/xk'; import { isHttpsOrigin } from '@botharness/host-protocol/route'; import { teamHostIdentity, teamRecord, type TeamResult, } from '@botharness/host-protocol/team-invitation'; -import { keyBytes, keyHex, secureRandom } from './encrypted-carrier'; +import { keyHex, secureRandom } from './encrypted-carrier'; import { encryptedSignIn, signInTransportFailure } from './encrypted-sign-in'; import type { HostEncryption, SavedHost } from './hosts'; +import { discoverSignInHost, matchesSavedSignInHost } from './sign-in-discovery'; const refusals = [ 'credentials-invalid', @@ -61,31 +60,17 @@ export async function signInOwnerDevice( ]); if (signal.aborted) return { ok: false, code: 'request-cancelled' }; try { - const response = await carrier.request(route + CONNECT_CHANNEL_PATH, { - method: 'GET', + const discovered = await discoverSignInHost({ + carrier, + route, redirect: 'error', signal, }); - if (response.status !== 200) return { ok: false, code: 'unreachable' }; - const discovery = teamRecord(JSON.parse(await response.text())); - const advertised = teamRecord(discovery['encryption']); - const host = teamHostIdentity({ - ...teamRecord(discovery['host']), - fingerprint: advertised['fingerprint'], - }); - const publicKey = advertised['publicKey']; - if (!host || typeof publicKey !== 'string' || !/^[a-f0-9]{64}$/u.test(publicKey)) - return { ok: false, code: 'response-invalid' }; + if (!discovered.ok) return discovered; + const { host, publicKey } = discovered.value; if (host.id === options.localHostId) return { ok: false, code: 'this-host' }; - if (noiseFingerprint(keyBytes(publicKey)) !== host.fingerprint) - return { ok: false, code: 'fingerprint-mismatch' }; const previous = options.previous?.(host.id, route); - if ( - previous && - (previous.hostId !== host.id || - (previous.encryption && previous.encryption.hostKey !== publicKey) || - (previous.member && previous.member.fingerprint !== host.fingerprint)) - ) + if (!matchesSavedSignInHost(previous, host, publicKey)) return { ok: false, code: 'fingerprint-mismatch' }; if (previous && options.allowExisting?.(previous) === false) return { ok: false, code: 'already-paired' }; diff --git a/packages/host-client/src/sign-in-discovery.ts b/packages/host-client/src/sign-in-discovery.ts new file mode 100644 index 0000000000..10c77ca8ab --- /dev/null +++ b/packages/host-client/src/sign-in-discovery.ts @@ -0,0 +1,70 @@ +import type { HostCarrier, HostRequest } from '@botharness/host-protocol/carrier'; +import { CONNECT_CHANNEL_PATH } from '@botharness/host-protocol/noise/channel'; +import { noiseFingerprint } from '@botharness/host-protocol/noise/xk'; +import { + teamHostIdentity, + teamRecord, + type TeamHostIdentity, + type TeamResult, +} from '@botharness/host-protocol/team-invitation'; +import { keyBytes } from './encrypted-carrier'; +import type { SavedHost } from './hosts'; + +export async function discoverSignInHost(options: { + carrier: HostCarrier; + route: string; + signal: AbortSignal; + redirect?: HostRequest['redirect']; + invitedHost?: TeamHostIdentity; +}): Promise< + TeamResult< + { host: TeamHostIdentity; publicKey: string }, + 'unreachable' | 'response-invalid' | 'fingerprint-mismatch' + > +> { + const { carrier, route, signal, redirect, invitedHost } = options; + const response = await carrier.request(route + CONNECT_CHANNEL_PATH, { + method: 'GET', + signal, + ...(redirect === undefined ? {} : { redirect }), + }); + if (response.status !== 200) return { ok: false, code: 'unreachable' }; + + const discovery = teamRecord(JSON.parse(await response.text())); + const identity = teamRecord(discovery['host']); + const encryption = teamRecord(discovery['encryption']); + const publicKey = encryption['publicKey']; + const host = teamHostIdentity({ + id: identity['id'], + name: invitedHost?.name ?? identity['name'], + fingerprint: encryption['fingerprint'], + }); + if (!host || typeof publicKey !== 'string' || !/^[a-f0-9]{64}$/u.test(publicKey)) + return { ok: false, code: invitedHost ? 'fingerprint-mismatch' : 'response-invalid' }; + if ( + noiseFingerprint(keyBytes(publicKey)) !== host.fingerprint || + (invitedHost && (invitedHost.id !== host.id || invitedHost.fingerprint !== host.fingerprint)) + ) + return { ok: false, code: 'fingerprint-mismatch' }; + return { ok: true, value: { host, publicKey } }; +} + +export function matchesSavedSignInHost( + saved: SavedHost | undefined, + host: TeamHostIdentity, + discoveredKey?: string, +): boolean { + if (!saved) return true; + const savedKey = saved.encryption?.hostKey; + if ( + discoveredKey !== undefined && + (saved.hostId !== host.id || (savedKey !== undefined && savedKey !== discoveredKey)) + ) + return false; + const pinnedFingerprint = + saved.member?.fingerprint ?? + (discoveredKey === undefined && savedKey !== undefined + ? noiseFingerprint(keyBytes(savedKey)) + : undefined); + return pinnedFingerprint === undefined || pinnedFingerprint === host.fingerprint; +} diff --git a/packages/host-client/src/team-client.ts b/packages/host-client/src/team-client.ts index b42b0ebb09..f4bd188b0a 100644 --- a/packages/host-client/src/team-client.ts +++ b/packages/host-client/src/team-client.ts @@ -1,9 +1,9 @@ import type { HostCarrier } from '@botharness/host-protocol/carrier'; import type { HostEncryption, SavedHost } from './hosts'; -import { encryptedCarrier, keyBytes, keyHex, secureRandom } from './encrypted-carrier'; +import { encryptedCarrier, keyHex, secureRandom } from './encrypted-carrier'; import { encryptedSignIn, signInRefusal, signInTransportFailure } from './encrypted-sign-in'; import { isConnectRoute } from '@botharness/host-protocol/route'; -import { noiseFingerprint } from '@botharness/host-protocol/noise/xk'; +import { discoverSignInHost } from './sign-in-discovery'; import { parseTeamInvitation, teamHostIdentity, @@ -133,26 +133,16 @@ async function signInTeamRoute( ): Promise> { const { invitation, route, signal } = options; try { - const response = await options.carrier.request(`${route}/botharness-device/channel`, { - method: 'GET', + const discovered = await discoverSignInHost({ + carrier: options.carrier, + route, signal, + invitedHost: invitation.host, }); - if (response.status !== 200) return { ok: false, code: 'unreachable' }; - const discovery = teamRecord(JSON.parse(await response.text())); - const host = teamRecord(discovery['host']); - const remote = teamRecord(discovery['encryption']); - const publicKey = remote['publicKey']; - if ( - host['id'] !== invitation.host.id || - typeof publicKey !== 'string' || - !/^[a-f0-9]{64}$/u.test(publicKey) || - noiseFingerprint(keyBytes(publicKey)) !== invitation.host.fingerprint || - remote['fingerprint'] !== invitation.host.fingerprint - ) - return { ok: false, code: 'fingerprint-mismatch' }; + if (!discovered.ok) return discovered; const encryption: HostEncryption = { protocol: 'connect-noise-xk-v1', - hostKey: publicKey, + hostKey: discovered.value.publicKey, deviceKey: keyHex(secureRandom(options.carrier)), }; const input = { diff --git a/packages/host-client/src/team-sign-in.ts b/packages/host-client/src/team-sign-in.ts index a82e7bc565..bc65309eff 100644 --- a/packages/host-client/src/team-sign-in.ts +++ b/packages/host-client/src/team-sign-in.ts @@ -1,20 +1,17 @@ import type { HostCarrier } from '@botharness/host-protocol/carrier'; -import { noiseFingerprint } from '@botharness/host-protocol/noise/xk'; import { parseTeamInvitation, - teamHostIdentity, teamHttpsRoute, - teamRecord, type TeamInvitation, type TeamHostIdentity, type TeamResult, type TeamErrorCode, } from '@botharness/host-protocol/team-invitation'; -import { keyBytes } from './encrypted-carrier'; import type { SavedHost } from './hosts'; import { prepareMemberIdentity, type HostMemberIdentity } from './member-identity'; import { changeTeamDevicePassword, signInTeamDevice } from './team-client'; import { revokePairing } from './pairing'; +import { discoverSignInHost, matchesSavedSignInHost } from './sign-in-discovery'; export type TeamSignInTarget = | { kind: 'invitation'; link: string } @@ -66,30 +63,13 @@ export async function addressInvitation(options: { AbortSignal.timeout(8_000), ...(options.signal ? [options.signal] : []), ]); - const response = await options.carrier.request(`${route}/botharness-device/channel`, { - method: 'GET', - signal, - }); - if (response.status !== 200) return { ok: false, code: 'unreachable' }; - const value = teamRecord(JSON.parse(await response.text())); - const encryption = teamRecord(value['encryption']); - const host = teamHostIdentity({ - ...teamRecord(value['host']), - fingerprint: encryption['fingerprint'], - }); - if ( - !host || - typeof encryption['publicKey'] !== 'string' || - !/^[a-f0-9]{64}$/u.test(encryption['publicKey']) - ) - return { ok: false, code: 'response-invalid' }; - if (noiseFingerprint(keyBytes(encryption['publicKey'])) !== host.fingerprint) - return { ok: false, code: 'fingerprint-mismatch' }; + const discovered = await discoverSignInHost({ carrier: options.carrier, route, signal }); + if (!discovered.ok) return discovered; return { ok: true, value: { v: 1, - host, + host: discovered.value.host, routes: [route], username, expiresAt: new Date(now() + 30 * 60_000).toISOString(), @@ -130,10 +110,7 @@ export async function prepareTeamSignIn(options: { invitation = found.value; } const previous = options.previous(invitation.host.id); - const pinned = - previous?.member?.fingerprint ?? - (previous?.encryption ? noiseFingerprint(keyBytes(previous.encryption.hostKey)) : undefined); - if (pinned !== undefined && pinned !== invitation.host.fingerprint) + if (!matchesSavedSignInHost(previous, invitation.host)) return { ok: false, code: 'fingerprint-mismatch' }; if (options.signal?.aborted) return { ok: false, code: 'request-cancelled' }; const abort = new AbortController(); diff --git a/packages/host-client/test/owner-sign-in.test.ts b/packages/host-client/test/owner-sign-in.test.ts index 74b30a5ec6..6690d2f625 100644 --- a/packages/host-client/test/owner-sign-in.test.ts +++ b/packages/host-client/test/owner-sign-in.test.ts @@ -130,6 +130,23 @@ describe('Owner password sign-in', () => { expect(test.wire.join('')).not.toContain(password); }); + it('rejects a channel fingerprint that does not match its advertised key', async () => { + const test = host(); + test.request.mockResolvedValueOnce({ + status: 200, + text: async () => + JSON.stringify({ + host: { id: 'studio', name: 'Studio' }, + encryption: { ...test.encryption, fingerprint: '01'.repeat(32) }, + }), + }); + expect(await signInOwnerDevice(test.input)).toEqual({ + ok: false, + code: 'fingerprint-mismatch', + }); + expect(test.openSocket).not.toHaveBeenCalled(); + }); + it('refuses an origin whose saved Host public key changed before opening a socket', async () => { const test = host(); expect( diff --git a/packages/host-client/test/team-sign-in.test.ts b/packages/host-client/test/team-sign-in.test.ts index c5f8c707cd..ef980faf68 100644 --- a/packages/host-client/test/team-sign-in.test.ts +++ b/packages/host-client/test/team-sign-in.test.ts @@ -106,8 +106,12 @@ describe('shared desktop Team sign-in flow', () => { target: { kind: 'address', route: invitation.routes[0]!, username: 'bob' }, }); expect(result.ok).toBe(true); - expect(test.request.mock.calls).toHaveLength(1); - expect(test.request.mock.calls[0]?.[1].method).toBe('GET'); + expect(test.request.mock.calls).toEqual([ + [ + invitation.routes[0] + '/botharness-device/channel', + { method: 'GET', signal: expect.any(AbortSignal) }, + ], + ]); if (!result.ok) return; expect(result.value.getSnapshot()).toEqual({ kind: 'fingerprint', @@ -115,6 +119,48 @@ describe('shared desktop Team sign-in flow', () => { username: 'bob', }); }); + it.each([ + { remoteId: 'other-host', remoteFingerprint: fingerprint }, + { remoteId: invitation.host.id, remoteFingerprint: '01'.repeat(32) }, + ])( + 'rejects a mismatched invitation Host before sending a password', + async ({ remoteId, remoteFingerprint }) => { + const test = setup(); + test.request.mockResolvedValueOnce({ + status: 200, + text: async () => + JSON.stringify({ + host: { id: remoteId }, + encryption: { + publicKey: Buffer.from(publicKey).toString('hex'), + fingerprint: remoteFingerprint, + }, + }), + }); + const flow = await test.prepare(); + expect(flow.confirmFingerprint(fingerprint).ok).toBe(true); + expect(await flow.signIn({ password: 'initial', deviceName: 'Desktop' })).toEqual({ + ok: false, + code: 'fingerprint-mismatch', + }); + expect(test.request).toHaveBeenCalledOnce(); + expect(test.request.mock.calls[0]?.[1].method).toBe('GET'); + }, + ); + it('uses the invitation name when the channel response omits the Host name', async () => { + const test = setup(false); + test.request.mockResolvedValueOnce({ + status: 200, + text: async () => + JSON.stringify({ + host: { id: invitation.host.id }, + encryption: { publicKey: Buffer.from(publicKey).toString('hex'), fingerprint }, + }), + }); + const flow = await test.prepare(); + expect(flow.confirmFingerprint(fingerprint).ok).toBe(true); + expect((await flow.signIn({ password: 'initial', deviceName: 'Desktop' })).ok).toBe(true); + }); it('refuses a changed pinned Host before any request', async () => { const test = setup(); test.setPrevious({ From f5432bcb2a7bd6c65682a2524bf9c873fe6a3ccb Mon Sep 17 00:00:00 2001 From: BotHarness Date: Sun, 22 Nov 2026 09:05:50 +0900 Subject: [PATCH 12/16] Share the Owner password dialog across settings Issue: #4898 Agent-Task: codex/local/01a1ff25-bf04-7871-9287-3625c3cb9dcd --- .../features/remote-hosts.md | 1 + .../verify-deepseekbot/features/team-mode.md | 1 + .../src/client/owner-password-dialog.tsx | 127 ++++++++++++++++++ .../owner-password-sign-in-settings.tsx | 83 +----------- packages/client/src/client/team-settings.tsx | 67 ++------- .../owner-password-sign-in-settings.test.tsx | 47 +++++++ 6 files changed, 194 insertions(+), 132 deletions(-) create mode 100644 packages/client/src/client/owner-password-dialog.tsx diff --git a/.agents/skills/verify-deepseekbot/features/remote-hosts.md b/.agents/skills/verify-deepseekbot/features/remote-hosts.md index c2c28d1bd7..39825f4892 100644 --- a/.agents/skills/verify-deepseekbot/features/remote-hosts.md +++ b/.agents/skills/verify-deepseekbot/features/remote-hosts.md @@ -6,6 +6,7 @@ The browser reads each Remote Host Feed through its own Paired Device and the sh - `packages/client/src/client/remote-host*.{ts,tsx}` - `packages/client/src/client/features/environments/remote-host-*.ts` +- `packages/client/src/client/owner-password-{dialog,sign-in-settings}.tsx` - `packages/host-client/src/{owner-sign-in,sign-in-discovery}.ts` - `packages/client/src/client/relationship{s,-settings}.{ts,tsx}` - `packages/core/src/devices/relationship*.ts` diff --git a/.agents/skills/verify-deepseekbot/features/team-mode.md b/.agents/skills/verify-deepseekbot/features/team-mode.md index 741fb8117f..3e7ad421e3 100644 --- a/.agents/skills/verify-deepseekbot/features/team-mode.md +++ b/.agents/skills/verify-deepseekbot/features/team-mode.md @@ -5,6 +5,7 @@ - `packages/core/src/features/team/plugin.ts` - `packages/core/src/team/**` - `packages/client/src/client/team-*` +- `packages/client/src/client/owner-password-dialog.tsx` - `packages/host-client/src/team-*.ts` - `packages/host-client/src/sign-in-discovery.ts` - `packages/host-client/src/shared/team-sign-in-page.ts` diff --git a/packages/client/src/client/owner-password-dialog.tsx b/packages/client/src/client/owner-password-dialog.tsx new file mode 100644 index 0000000000..d679d0a45a --- /dev/null +++ b/packages/client/src/client/owner-password-dialog.tsx @@ -0,0 +1,127 @@ +import { useState, type ReactElement } from 'react'; +import { FieldStack, TextField } from './ds/field.js'; +import { FormDialog } from './ds/form-dialog.js'; +import type { BotHarnessTranslate } from './locale.js'; +import { TEAM_PASSWORD_MIN_LENGTH, validUsername } from './team-bridge.js'; + +type OwnerPasswordDialogProps = { + t: BotHarnessTranslate; + busy: boolean; + error: string | undefined; + onCancel(): void; +} & ( + | { kind: 'standalone'; onSubmit(username: string, password: string): void } + | { + kind: 'team'; + hasPassword: boolean; + thenEnable: boolean; + onSubmit(password: string, current: string | undefined): void; + } +); + +export function OwnerPasswordDialog(props: OwnerPasswordDialogProps): ReactElement { + const { t, busy, error, onCancel } = props; + const standalone = props.kind === 'standalone'; + const hasPassword = !standalone && props.hasPassword; + const thenEnable = standalone || props.thenEnable; + const [username, setUsername] = useState(''); + const [current, setCurrent] = useState(''); + const [password, setPassword] = useState(''); + const [confirmation, setConfirmation] = useState(''); + const normalizedUsername = username.trim(); + const passwordTooLong = standalone && new TextEncoder().encode(password).length > 1024; + const passwordTooShort = password.length < TEAM_PASSWORD_MIN_LENGTH; + const ready = + (!standalone || validUsername(normalizedUsername)) && + (!hasPassword || current.length > 0) && + !passwordTooLong && + !passwordTooShort && + password === confirmation; + const passwordError = passwordTooLong + ? t('connections.ownerSignIn.passwordTooLong') + : !standalone && password.length > 0 && passwordTooShort + ? t('team.error.passwordWeak') + : undefined; + const fields = ( + <> + {standalone ? ( + + ) : null} + {hasPassword ? ( + + ) : null} + + 0 && confirmation !== password + ? t('team.password.mismatch') + : undefined + } + onChange={setConfirmation} + /> + + ); + return ( + { + if (standalone) props.onSubmit(normalizedUsername, password); + else props.onSubmit(password, hasPassword ? current : undefined); + }} + > + {standalone ? fields : {fields}} + + ); +} diff --git a/packages/client/src/client/owner-password-sign-in-settings.tsx b/packages/client/src/client/owner-password-sign-in-settings.tsx index 6a1e30c6ca..97cbbb4045 100644 --- a/packages/client/src/client/owner-password-sign-in-settings.tsx +++ b/packages/client/src/client/owner-password-sign-in-settings.tsx @@ -1,15 +1,14 @@ import { useRef, useState, type ReactElement } from 'react'; import { BridgeCallError, unwrap, type BridgeCall } from './bridge-transport.js'; import { Button } from './ds/button.js'; -import { TextField } from './ds/field.js'; -import { FormDialog } from './ds/form-dialog.js'; import { Note } from './ds/note.js'; import { SettingsRow } from './ds/settings-row.js'; import { Switch } from './ds/switch.js'; import type { BotHarnessTranslate } from './locale.js'; import { memberPage } from './member-page.js'; import { useMountedResource } from './mounted-resource.js'; -import { record, TEAM_PASSWORD_MIN_LENGTH, teamRefusal } from './team-bridge.js'; +import { OwnerPasswordDialog } from './owner-password-dialog.js'; +import { record, teamRefusal } from './team-bridge.js'; import { refreshTeamMode } from './team-state.js'; type SignInView = { enabled: false } | { enabled: boolean; username: string }; @@ -165,89 +164,19 @@ export function OwnerPasswordSignInSettings({ {!setup && error !== undefined ? {error} : null}
{setup ? ( - { + onCancel={() => { if (busy) return; setError(undefined); setSetup(false); }} - submit={(username, password) => void save({ enabled: true, username, password })} + onSubmit={(username, password) => void save({ enabled: true, username, password })} /> ) : null} ); } - -function SetupDialog({ - t, - busy, - error, - cancel, - submit, -}: { - t: BotHarnessTranslate; - busy: boolean; - error: string | undefined; - cancel(): void; - submit(username: string, password: string): void; -}): ReactElement { - const [username, setUsername] = useState(''); - const [password, setPassword] = useState(''); - const [confirmation, setConfirmation] = useState(''); - const validUsername = /^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username.trim()); - const passwordTooLong = new TextEncoder().encode(password).length > 1024; - const validPassword = password.length >= TEAM_PASSWORD_MIN_LENGTH && !passwordTooLong; - return ( - submit(username.trim(), password)} - > - - - 0 && confirmation !== password - ? t('team.password.mismatch') - : undefined - } - onChange={setConfirmation} - /> - - ); -} diff --git a/packages/client/src/client/team-settings.tsx b/packages/client/src/client/team-settings.tsx index a485153430..90042204f1 100644 --- a/packages/client/src/client/team-settings.tsx +++ b/packages/client/src/client/team-settings.tsx @@ -15,12 +15,12 @@ import type { BotHarnessKey, BotHarnessTranslate } from './locale.js'; import { TeamUsageSection } from './team-usage-section.js'; import { USAGE_VIEW } from './team-usage.js'; import { useMountedResource } from './mounted-resource.js'; +import { OwnerPasswordDialog } from './owner-password-dialog.js'; import { AuditLogSection, PrivateContentSection } from './team-audit.js'; import { AUDIT_VIEW, PRIVATE_VIEW } from './team-audit-bridge.js'; import { SpacesSection } from './team-spaces.js'; import { TEAM_ENTRY_PATH, - TEAM_PASSWORD_MIN_LENGTH, createMember, loadMembers, loadTeamMode, @@ -534,7 +534,7 @@ export function TeamSection({ call, t }: TeamSectionProps): ReactElement { {auditView} {dialog?.kind === 'owner-password' ? ( - ; }): ReactElement { - const [current, setCurrent] = useState(''); - const [password, setPassword] = useState(''); - const [confirm, setConfirm] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(); - const short = password.length > 0 && password.length < TEAM_PASSWORD_MIN_LENGTH; - const mismatch = confirm.length > 0 && confirm !== password; - const ready = - password.length >= TEAM_PASSWORD_MIN_LENGTH && - confirm === password && - (!hasPassword || current.length > 0); return ( - {error}} + error={error} onCancel={onCancel} - onSubmit={() => { + onSubmit={(password, current) => { setBusy(true); setError(undefined); - onSubmit(password, hasPassword ? current : undefined) + onSubmit(password, current) .catch((failure: unknown) => setError(teamErrorText(t, failure))) .finally(() => setBusy(false)); }} - > - - {hasPassword ? ( - - ) : null} - - - - + /> ); } diff --git a/packages/client/test/owner-password-sign-in-settings.test.tsx b/packages/client/test/owner-password-sign-in-settings.test.tsx index 38d07e965d..5a160a8409 100644 --- a/packages/client/test/owner-password-sign-in-settings.test.tsx +++ b/packages/client/test/owner-password-sign-in-settings.test.tsx @@ -3,9 +3,11 @@ import { act } from 'react'; import { createRoot } from 'react-dom/client'; import { Simulate } from 'react-dom/test-utils'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { fakeTeamMode } from '../../host-client/test/reader-fixtures.js'; import type { BridgeCall } from '../src/client/bridge.js'; import { ConnectionsPage } from '../src/client/connections-dialog.js'; import { zhTranslate } from '../src/client/locale.js'; +import { TeamSection } from '../src/client/team-settings.js'; vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({ ...(await import('./primitive-mocks.js')).shellPrimitives(), @@ -129,6 +131,51 @@ it('preserves the last settings value if a toggle is refused', async () => { expect(host.textContent).not.toContain('保存失败,再试一次。'); }); +it('requires the current password and retains Team settings error handling', async () => { + const mode = { ...fakeTeamMode(), ownerPasswordSet: true }; + let refuse = true; + const call = vi.fn(async (method) => { + if (method === 'teamOwnerPasswordSet' && refuse) { + return { + ok: false, + error: { code: 'credentials-invalid', message: 'credentials-invalid', details: {} }, + }; + } + return { + ok: true, + value: method === 'teamMode' || method === 'teamOwnerPasswordSet' ? mode : [], + }; + }); + await act(async () => root.render()); + await act(async () => button(zhTranslate('team.ownerPassword.change')).click()); + const dialog = document.querySelector('[role="dialog"]'); + if (!dialog) throw new Error('Missing change-password dialog'); + const submit = button(zhTranslate('team.save'), dialog); + await fill(zhTranslate('team.password.new'), 'new-test-password'); + await fill(zhTranslate('team.password.confirm'), 'new-test-password'); + expect(submit.disabled).toBe(true); + await fill(zhTranslate('team.password.current'), 'old-test-password'); + await act(async () => submit.click()); + expect([...dialog.querySelectorAll('[role="alert"]')].map((node) => node.textContent)).toEqual([ + zhTranslate('team.error.credentialsInvalid'), + ]); + refuse = false; + await act(async () => submit.click()); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + expect(call.mock.calls.filter(([method]) => method === 'teamOwnerPasswordSet')).toEqual([ + [ + 'teamOwnerPasswordSet', + { password: 'new-test-password', current: 'old-test-password' }, + undefined, + ], + [ + 'teamOwnerPasswordSet', + { password: 'new-test-password', current: 'old-test-password' }, + undefined, + ], + ]); +}); + it('keeps the Owner controls unavailable in a member shell', async () => { vi.stubGlobal('__DSH_REMOTE_ACCESS__', { owner: false }); const call = vi.fn(async () => ({ From 304717ad65b7021bb9d7bf5b4e02f1f3d43a0249 Mon Sep 17 00:00:00 2001 From: BotHarness Date: Mon, 23 Nov 2026 01:33:57 +0900 Subject: [PATCH 13/16] Use subscription list cards for remote Connections Issue: #4899 Agent-Task: codex/local/01a20227-5819-7d43-ab77-f7e1ed665c7e --- .../features/remote-hosts.md | 3 + .../client/src/client/connection-hosts.tsx | 372 ++++++++++-------- packages/client/src/client/ds/list-card.tsx | 6 +- .../environments/connections-locale.ts | 2 + .../client/test/connection-hosts.test.tsx | 10 +- scripts/cli-ui-inventory.json | 2 + scripts/cli-ui-inventory.mjs | 7 +- scripts/test/cli-ui-inventory.test.mjs | 9 + 8 files changed, 241 insertions(+), 170 deletions(-) diff --git a/.agents/skills/verify-deepseekbot/features/remote-hosts.md b/.agents/skills/verify-deepseekbot/features/remote-hosts.md index 84a03ef232..66951a2982 100644 --- a/.agents/skills/verify-deepseekbot/features/remote-hosts.md +++ b/.agents/skills/verify-deepseekbot/features/remote-hosts.md @@ -7,6 +7,7 @@ The browser reads each Remote Host Feed through its own Paired Device and the sh - `packages/client/src/client/remote-host*.{ts,tsx}` - `packages/client/src/client/features/environments/remote-host-*.ts` - `packages/client/src/client/owner-password-{dialog,sign-in-settings}.tsx` +- `packages/client/src/client/connection-hosts.tsx` - `packages/host-client/src/{owner-sign-in,sign-in-discovery}.ts` - `packages/client/src/client/relationship{s,-settings}.{ts,tsx}` - `packages/core/src/devices/relationship*.ts` @@ -32,6 +33,8 @@ On a fresh Host with Team mode off, enroll two Owner devices by password and one For CLI parity, pass the private JSON containing `current` and `password` on stdin to `team-mode owner-password --password-stdin --sign-out-others=true --confirm`. Compare `devices` and `device-probe` results for password and QR grants, and repeat with `--sign-out-others=false`. Redact credentials from visual and console evidence. +In remote Connections, check that route selection, route status and route actions share a list card, and that each paired device has its own row and revoke action in the device card. Use a narrow settings window with a long route address to check that the address and action remain readable. Compare the device list with the target Host's `devices` output. + ## Reciprocal relationship (E1) Use fresh schema144 Homes after published Team141–143; do not launch internal Environment141–143 preview databases with this source. Relationship management is current-Owner-only: member/Admin HTTP carriers and CLI `--as` must refuse list/initiate/approve/enroll/disconnect. Transfer Owner and require old derived credentials and pending old-Owner offers to refuse; a newly enrolled Client records the new Owner Human. A valid current-Owner credential still cannot bypass inactive-relationship admission. Retain private Source Event Human readback, spoofed Human rejection and private-Bot access refusals through the same per-Human bridge factory. diff --git a/packages/client/src/client/connection-hosts.tsx b/packages/client/src/client/connection-hosts.tsx index a4cfeb7496..c266573483 100644 --- a/packages/client/src/client/connection-hosts.tsx +++ b/packages/client/src/client/connection-hosts.tsx @@ -14,6 +14,8 @@ import { import { parseConnectedHosts } from './connect-account-hosts.js'; import { useMountedResource } from './mounted-resource.js'; import { SettingsRow, SettingsSection } from './ds/settings-row.js'; +import { Icon } from './ds/icon.js'; +import { ListCard, ListCardItem } from './ds/list-card.js'; import { StatusDisclosure } from './ds/status-block.js'; import { Note } from './ds/note.js'; import { ConfirmDialog } from './ds/form-dialog.js'; @@ -153,6 +155,7 @@ function HostDetailsSession({ } }; const observed = observedHost(remote); + const devices = managed?.devices.filter((device) => !device.revoked) ?? []; const mutationBlocked = busy || remote.host.pendingConnection !== undefined || @@ -180,75 +183,135 @@ function HostDetailsSession({ ) : null} - route.address), - ...(observed.routePreference === 'automatic' ? [] : [observed.routePreference]), - ]), - ].map((route) => ({ - value: route, - label: `${routeLabel(route, t)} · ${route}`, - })), - ]} - onChange={(route) => void perform({ action: 'select-route', route, confirm: true })} - /> - } - /> - {observed.routeChangePending ? {t('connections.hosts.switchPending')} : null} - {observed.routePreference !== 'automatic' ? ( - <> - {t('connections.hosts.manualHint')} - + + ) : null} + + ) : undefined } - > - {t('connections.hosts.returnAutomatic')} - - - ) : null} - {observed.routes.map((route) => ( - void perform({ action: 'test-route', route: route.address })} - > - {t('connections.hosts.testRoute')} - - } - /> - ))} + trailing={ +