diff --git a/.agents/skills/verify-deepseekbot/features/phone-pairing.md b/.agents/skills/verify-deepseekbot/features/phone-pairing.md
index b44a7a1640..8fe3dc517f 100644
--- a/.agents/skills/verify-deepseekbot/features/phone-pairing.md
+++ b/.agents/skills/verify-deepseekbot/features/phone-pairing.md
@@ -2,6 +2,10 @@
## Sources
+- `apps/mobile/app/pair/{_layout,index,team,tailscale}.tsx`
+- `apps/mobile/src/ui/shell/pair-scanner.tsx`
+- `apps/mobile/src/host/connect-input.ts`
+- `apps/mobile/src/host/{host-session,native-carrier}.ts`
- `apps/mobile/app/member-pairing.tsx`
- `apps/mobile/src/host/{account-pairing,pairing-image}.ts`
- `apps/mobile/src/ui/pairing-failure.ts`
@@ -16,6 +20,12 @@
- Paired Device
- Host Relationship
+## Owner sign-in over HTTPS (#4900)
+
+In the shared device QA lanes, use two isolated Hosts with separate Feed markers and trusted HTTPS addresses. On each platform, start without a saved Host, then open **Pair with your computer**, type the Host's HTTPS address into the scan-or-enter field and choose **Connect**. Choose **Sign in with username and password**, sign in with the Owner username and password, and open **View Host fingerprint** to compare it. **Approve on the computer** must show where to open the pairing code and return to the scanner. Repeat with a member username and confirm the member path continues to the password change. A Host without password sign-in must show the scan-a-code guidance before any password field. Paste an invitation link into the same field and confirm it opens member sign-in. The Host records an Owner password-enrolled device and the phone opens its Feed. Open the workspace drawer, choose **Add computer**, and sign in to the second Host through the same entry. Open each Feed and verify the markers stay scoped to their Host. Confirm a duplicate attempt leaves the original saved grant intact.
+
+Exercise an untrusted certificate, a redirect and a changed key for a saved Host. In each case, verify the Host receives no password. Correct a wrong credential and retry with the address and username still populated. Verify QR pairing, fingerprint comparison and approval from the same menu. Repeat the form with the software keyboard and default, intermediate and maximum text sizes in both themes. Save redacted visuals for the menu and form on each platform.
+
## Connect desktop self-check (#4170)
In a task-owned signed-in Host, open Connections → Tobs Connect and verify automatic check progress after sign-in/connector recovery. Compare the card and `deepseekbot connect-check` with `connect-status` through the same authenticated Host. A running connector alone must remain neutral. Require relay online plus a fresh Host-pinned public encrypted handshake before success; observe checked time and copy only bounded diagnostics. Inject task-owned DNS/TLS/HTTP/handshake failures, retry after recovery, expire the observation and fail the snapshot/retry request: none may retain green success. Opening the dialog must not start extra probes. Transient public failures retry at most four attempts with 1/3/6-second waits within the same 20-second deadline; certificate/identity failures refuse immediately, including incomplete certificate chains. Handshake payloads are limited to1KiB without compression before Noise decoding. A stale checking snapshot must allow retry when no local request is active; manual requests time out after25seconds and abort on card close. Each completed check refreshes the account computer list once without closing an existing management confirmation. A health refresh that interrupts a post-revoke list read must start a replacement read and leave controls usable. Do not change production DNS, other Host bindings or device grants. Record official-service versus isolated transport-fixture proof separately; desktop self-check does not qualify every phone network or reproduce a customer fault.
diff --git a/apps/mobile/app/pair/_layout.tsx b/apps/mobile/app/pair/_layout.tsx
index dd86ae0c1f..575a3175a4 100644
--- a/apps/mobile/app/pair/_layout.tsx
+++ b/apps/mobile/app/pair/_layout.tsx
@@ -10,7 +10,7 @@ export default function PairLayout() {
-
+
);
}
diff --git a/apps/mobile/app/pair/index.tsx b/apps/mobile/app/pair/index.tsx
index 054d193874..01e9b1d9e4 100644
--- a/apps/mobile/app/pair/index.tsx
+++ b/apps/mobile/app/pair/index.tsx
@@ -1,20 +1,18 @@
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback, useRef, useState } from 'react';
-import { Linking, ScrollView } from 'react-native';
+import { Linking } from 'react-native';
import { cloudAvailable } from '../../src/cloud/available';
import { pairingLinkMode } from '@botharness/host-client/pairing';
import { SHEET_GROUP } from '../../src/ui/chat/sheet';
-import { useDesignTheme } from '../../src/ui/design/theme';
-import { space } from '../../src/ui/design/tokens';
import { Button } from '../../src/ui/primitives/button';
import { SettingsRow, SettingsSection } from '../../src/ui/primitives/settings-row';
import { Text } from '../../src/ui/primitives/text';
+import { PairScanner } from '../../src/ui/shell/pair-scanner';
import { useStrings } from '../../src/ui/strings';
export default function PairChoiceScreen() {
const t = useStrings();
- const theme = useDesignTheme();
const router = useRouter();
const [linkError, setLinkError] = useState(false);
const params = useLocalSearchParams<{ p?: string; account?: string }>();
@@ -41,43 +39,8 @@ export default function PairChoiceScreen() {
);
return (
-
-
- router.push({ pathname: '/pair/tailscale', params: { mode: 'private' } })}
- />
-
- router.push({
- pathname: '/pair/tailscale',
- params: { mode: 'lan' },
- })
- }
- />
- router.push('/pair/team')}
- />
+
+
router.push('/pair/account')}
/>
router.push('/pair/tailscale')}
+ title={t.pairGuide.open}
+ detail={t.pairChoice.needs}
+ icon="open"
+ onPress={() => {
+ setLinkError(false);
+ void Linking.openURL(t.pairGuide.url).catch(() => setLinkError(true));
+ }}
/>
-
+
);
}
diff --git a/apps/mobile/app/pair/tailscale.tsx b/apps/mobile/app/pair/tailscale.tsx
index dd4096141a..8a805cdaca 100644
--- a/apps/mobile/app/pair/tailscale.tsx
+++ b/apps/mobile/app/pair/tailscale.tsx
@@ -1,247 +1,38 @@
-import { CameraView, useCameraPermissions } from 'expo-camera';
-import { Stack, useFocusEffect, useLocalSearchParams } from 'expo-router';
-import { useCallback, useRef, useState } from 'react';
-import { Pressable, View, useWindowDimensions } from 'react-native';
+import { Stack, useLocalSearchParams } from 'expo-router';
-import { readPairingImage, type PairingImageResult } from '../../src/host/pairing-image';
-import type { PairingMethod } from '@botharness/host-client/telemetry/schema';
-import { HOST_NAME_MAX } from '@botharness/host-client/ui/design/host-look';
-import { useDesignTheme } from '../../src/ui/design/theme';
-import { pairingScan, radius, space } from '../../src/ui/design/tokens';
-import { clearsPastedLink } from '../../src/ui/pairing-failure';
-import { Button } from '../../src/ui/primitives/button';
-import { ConnectionNameField } from '../../src/ui/primitives/connection-name-field';
-import { KeyboardFormScroll } from '../../src/ui/primitives/keyboard-form';
import { Text } from '../../src/ui/primitives/text';
-import { TextField } from '../../src/ui/primitives/text-field';
-import { DesktopPath } from '../../src/ui/shell/desktop-path';
-import { PairingFailureNotice } from '../../src/ui/shell/pairing-failure-notice';
-import { PairingVerification } from '../../src/ui/shell/pairing-verification';
-import { usePairing } from '../../src/ui/shell/use-pairing';
+import { PairScanner } from '../../src/ui/shell/pair-scanner';
import { useStrings } from '../../src/ui/strings';
export default function PairTailscaleScreen() {
const t = useStrings();
- const theme = useDesignTheme();
- const { width } = useWindowDimensions();
- const scan = Math.min(width * pairingScan.widthRatio, pairingScan.maxSize);
const params = useLocalSearchParams<{ p?: string; mode?: string }>();
- const [permission, requestPermission] = useCameraPermissions();
- const [link, setLink] = useState('');
- const [focused, setFocused] = useState(false);
- const [readingImage, setReadingImage] = useState(false);
- const [imageError, setImageError] =
- useState['code']>();
- const imageOperation = useRef(undefined);
- const active = useRef(false);
- const submitting = useRef(false);
- const deepLinked = useRef(false);
- const pairing = usePairing();
-
- const pair = async (text: string, method: PairingMethod): Promise => {
- if (!active.current || imageOperation.current || submitting.current) return;
- submitting.current = true;
- setImageError(undefined);
- try {
- const failure = await pairing.pair(text, method);
- if (active.current && failure !== undefined && clearsPastedLink(failure, method)) setLink('');
- } finally {
- submitting.current = false;
- }
- };
-
- const chooseImage = async (): Promise => {
- if (!active.current || imageOperation.current || submitting.current || pairing.busy) return;
- const operation = new AbortController();
- imageOperation.current = operation;
- setReadingImage(true);
- setImageError(undefined);
- const result = await readPairingImage(operation.signal);
- if (operation.signal.aborted || imageOperation.current !== operation) return;
- imageOperation.current = undefined;
- setReadingImage(false);
- if (result.kind === 'error') setImageError(result.code);
- else if (result.kind === 'link') {
- pairing.forget();
- await pair(result.link, 'image');
- }
- };
-
- const retry = async (): Promise => {
- if (!active.current || imageOperation.current || submitting.current) return;
- submitting.current = true;
- try {
- await pairing.retry();
- } finally {
- submitting.current = false;
- }
- };
-
- useFocusEffect(
- useCallback(() => {
- active.current = true;
- setFocused(true);
- if (typeof params.p === 'string' && !deepLinked.current) {
- deepLinked.current = true;
- void pair(`deepseekbot://pair?p=${params.p}`, 'deep_link');
- }
- return () => {
- active.current = false;
- imageOperation.current?.abort();
- imageOperation.current = undefined;
- setReadingImage(false);
- setFocused(false);
- pairing.abort();
- };
- }, [params.p]),
- );
-
const title =
params.mode === 'private'
? t.pairChoice.private
: params.mode === 'lan'
? t.pairChoice.lan
: t.pairChoice.tailscale;
- if (pairing.busy)
- return (
- <>
-
-
- >
- );
-
return (
-
-
- {params.mode === 'lan' ? null : (
-
- {params.mode === 'private' ? t.pairChoice.privateHint : t.pairChoice.tailscaleHint}
-
- )}
-
-
-
- {permission?.granted ? (
- focused &&
- !readingImage && (
- void pair(data, 'qr')}
- />
- )
- ) : (
- void requestPermission()}
- accessibilityRole="button"
- style={{
- padding: space.x5,
- minHeight: theme.touch,
- justifyContent: 'center',
- }}
- >
-
- {t.allowCamera}
-
-
- )}
-
-
- {imageError !== undefined ? (
-
- {t.pairImage[imageError]}
-
- ) : pairing.error !== undefined ? (
-
- ) : null}
- {pairing.canRetry && imageError === undefined ? (
-
+ >
);
}
diff --git a/apps/mobile/app/pair/team.tsx b/apps/mobile/app/pair/team.tsx
index c35ec2011a..bfcd0a3107 100644
--- a/apps/mobile/app/pair/team.tsx
+++ b/apps/mobile/app/pair/team.tsx
@@ -1,6 +1,6 @@
import Constants from 'expo-constants';
-import { useLocalSearchParams, useRouter } from 'expo-router';
-import { useRef, useState } from 'react';
+import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
+import { useCallback, useRef, useState } from 'react';
import { Platform, View } from 'react-native';
import { computerEnvironmentKey } from '../../src/host/conversation-environments';
@@ -17,13 +17,20 @@ import {
type TeamErrorCode,
type TeamInvitation,
} from '@botharness/host-client/team-client';
-import { addressInvitation } from '@botharness/host-client/team-sign-in';
-import { pinnedFingerprint, teamAddressRoute } from '../../src/host/team-address';
+import {
+ discoverHostAddress,
+ type HostAddressDiscovery,
+} from '@botharness/host-client/password-sign-in';
+import { pinnedFingerprint } from '../../src/host/team-address';
import { space } from '../../src/ui/design/tokens';
import { Button } from '../../src/ui/primitives/button';
import { CopyableFingerprint } from '../../src/ui/primitives/copyable-fingerprint';
+import { SettingsRow, SettingsSection } from '../../src/ui/primitives/settings-row';
+import { SHEET_GROUP } from '../../src/ui/chat/sheet';
+import { DesktopPath } from '../../src/ui/shell/desktop-path';
import { KeyboardFormScroll } from '../../src/ui/primitives/keyboard-form';
import { Text } from '../../src/ui/primitives/text';
+import { labelInField } from '../../src/ui/primitives/field-label';
import { TextField } from '../../src/ui/primitives/text-field';
import { closeWorkspacePageWhenShown } from '../../src/ui/shell/workspace-paging';
import { useStrings } from '../../src/ui/strings';
@@ -36,7 +43,23 @@ type Step =
| { kind: 'change'; host: SavedHost; current: string }
| { kind: 'switch'; host: SavedHost }
| { kind: 'address' }
- | { kind: 'fingerprint'; invitation: TeamInvitation };
+ | { kind: 'connecting' }
+ | { kind: 'choose'; found: HostAddressDiscovery }
+ | { kind: 'host'; found: HostAddressDiscovery }
+ | { kind: 'needs-code'; found: HostAddressDiscovery; chosen?: boolean };
+
+function Labeled({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+
+ {labelInField ? null : (
+
+ {label}
+
+ )}
+ {children}
+
+ );
+}
function phoneName(): string {
return Constants.deviceName ?? (Platform.OS === 'ios' ? 'iPhone' : 'Android phone');
@@ -46,7 +69,9 @@ function initialStep(
link: string | undefined,
hostId: string | undefined,
pick = false,
+ address?: string,
): { step: Step; error?: TeamErrorCode | string } {
+ if (address !== undefined) return { step: { kind: 'connecting' } };
if (hostId !== undefined) {
const saved = hostSession.getState().hosts.find((host) => host.hostId === hostId);
const invitation = saved === undefined ? undefined : signInAgainInvitation(saved);
@@ -67,12 +92,18 @@ function initialStep(
export default function TeamSignInScreen() {
const t = useStrings();
const router = useRouter();
- const params = useLocalSearchParams<{ i?: string; host?: string; switch?: string }>();
+ const params = useLocalSearchParams<{
+ i?: string;
+ host?: string;
+ switch?: string;
+ address?: string;
+ }>();
const first = useRef(
initialStep(
typeof params.i === 'string' ? params.i : undefined,
typeof params.host === 'string' ? params.host : undefined,
params.switch === '1',
+ typeof params.address === 'string' ? params.address : undefined,
),
);
const [step, setStep] = useState(first.current.step);
@@ -80,14 +111,31 @@ export default function TeamSignInScreen() {
const [retryAfter, setRetryAfter] = useState();
const [busy, setBusy] = useState(false);
const [link, setLink] = useState('');
- const [address, setAddress] = useState('');
+ const [address, setAddress] = useState(typeof params.address === 'string' ? params.address : '');
+ const pending = useRef(undefined);
+ const [fingerprintShown, setFingerprintShown] = useState(false);
+ const discovered = useRef(false);
+ useFocusEffect(
+ useCallback(() => {
+ if (!discovered.current && first.current.step.kind === 'connecting') {
+ discovered.current = true;
+ void discover(address);
+ }
+ return () => pending.current?.abort();
+ }, []),
+ );
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [next, setNext] = useState('');
const [confirm, setConfirm] = useState('');
const message = (code: string): string => {
- const copy = t.teamSignIn.errors as Record;
+ const copy: Record = {
+ ...(t.teamSignIn.errors as Record),
+ 'owner-sign-in-disabled': t.ownerSignIn.disabled,
+ 'already-paired': t.ownerSignIn.alreadyPaired,
+ ...(step.kind === 'host' ? { 'credentials-invalid': t.ownerSignIn.credentialsInvalid } : {}),
+ };
const text = copy[code] ?? copy['generic']!;
return text.replace('{seconds}', String(retryAfter ?? 60));
};
@@ -129,28 +177,72 @@ export default function TeamSignInScreen() {
setStep({ kind: 'link' });
};
- const lookUp = async (): Promise => {
- const route = teamAddressRoute(address);
- if (route === undefined) return setError('insecure-transport');
+ const discover = async (input: string): Promise => {
+ const request = new AbortController();
+ pending.current?.abort();
+ pending.current = request;
setBusy(true);
setError(undefined);
- const found = await addressInvitation({
- route,
- username: username.trim().toLowerCase(),
+ setStep({ kind: 'connecting' });
+ const found = await discoverHostAddress({
carrier: nativeCarrier(),
+ input,
+ signal: request.signal,
});
+ if (request.signal.aborted) return;
+ pending.current = undefined;
setBusy(false);
- if (!found.ok) return setError(found.code);
+ if (!found.ok) {
+ setStep({ kind: 'address' });
+ return setError(found.code);
+ }
const pinned = pinnedFingerprint(hostSession.getState().hosts, found.value.host.id);
- if (pinned !== undefined && pinned !== found.value.host.fingerprint)
+ if (pinned !== undefined && pinned !== found.value.host.fingerprint) {
+ setStep({ kind: 'address' });
return setError('fingerprint-mismatch');
+ }
setStep(
- pinned === undefined
- ? { kind: 'fingerprint', invitation: found.value }
- : { kind: 'sign-in', invitation: found.value },
+ found.value.signIn?.password === false
+ ? { kind: 'needs-code', found: found.value }
+ : { kind: 'choose', found: found.value },
);
};
+ const passwordSignIn = async (found: HostAddressDiscovery): Promise => {
+ if (pending.current || username.trim() === '' || password === '') return;
+ const request = new AbortController();
+ pending.current = request;
+ setBusy(true);
+ setError(undefined);
+ const current = password;
+ const result = await hostSession.signInPassword({
+ route: found.route,
+ username: username.trim(),
+ password: current,
+ deviceName: phoneName(),
+ signal: request.signal,
+ });
+ pending.current = undefined;
+ setPassword('');
+ if (request.signal.aborted) return;
+ if (!result.ok) {
+ setBusy(false);
+ setRetryAfter(result.retryAfterSeconds);
+ if (result.code === 'request-cancelled') return;
+ if (result.code === 'password-sign-in-unavailable')
+ return setStep({ kind: 'needs-code', found });
+ return setError(result.code);
+ }
+ const { role, ...host } = result.value;
+ if (role === 'owner') return land(host.hostId);
+ if (host.member?.mustChangePassword === true) {
+ setBusy(false);
+ return setStep({ kind: 'change', host, current });
+ }
+ if (await persist(host)) return land(host.hostId);
+ setBusy(false);
+ };
+
const openLink = (): void => {
const parsed = parseTeamInvitation(link.trim());
if (!parsed.ok) {
@@ -273,39 +365,24 @@ export default function TeamSignInScreen() {
>
) : step.kind === 'address' ? (
<>
- {t.teamSignIn.manualHint}
- {
- setAddress(value);
- setError(undefined);
- }}
- autoCapitalize="none"
- autoCorrect={false}
- keyboardType="url"
- returnKeyType="next"
- editable={!busy}
- />
- {
- setUsername(value);
- setError(undefined);
- }}
- textContentType="username"
- autoComplete="username"
- autoCapitalize="none"
- autoCorrect={false}
- returnKeyType="go"
- editable={!busy}
- onSubmitEditing={() => void lookUp()}
- />
+
+ {
+ setAddress(value);
+ setError(undefined);
+ }}
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ returnKeyType="go"
+ editable={!busy}
+ onSubmitEditing={() => void discover(address)}
+ />
+
{errorText}
void lookUp()}
+ disabled={busy || address.trim() === ''}
+ onPress={() => void discover(address)}
+ />
+ >
+ ) : step.kind === 'connecting' ? (
+
+ {t.teamSignIn.connecting}
+
+ ) : step.kind === 'choose' ? (
+ <>
+
+ {t.teamSignIn.connectTo.replace('{host}', step.found.host.name)}
+
+
+ {
+ setError(undefined);
+ setFingerprintShown(false);
+ setStep({ kind: 'host', found: step.found });
+ }}
+ />
+ setStep({ kind: 'needs-code', found: step.found, chosen: true })}
+ />
+
+ >
+ ) : step.kind === 'needs-code' ? (
+ <>
+
+ {t.teamSignIn.connectTo.replace('{host}', step.found.host.name)}
+
+
+ {step.chosen === true ? t.teamSignIn.approveHint : t.teamSignIn.needsCode}
+
+
+ router.back()}
/>
>
- ) : step.kind === 'fingerprint' ? (
+ ) : step.kind === 'host' ? (
<>
- {t.teamSignIn.title.replace('{host}', step.invitation.host.name)}
+ {t.teamSignIn.title.replace('{host}', step.found.host.name)}
- {t.teamSignIn.fingerprintHint}
-
+
+ {
+ setUsername(value);
+ setError(undefined);
+ }}
+ textContentType="username"
+ autoComplete="username"
+ autoCapitalize="none"
+ autoCorrect={false}
+ maxLength={32}
+ returnKeyType="next"
+ editable={!busy}
+ />
+
+
+ {
+ setPassword(value);
+ setError(undefined);
+ }}
+ secureTextEntry
+ textContentType="password"
+ autoComplete="current-password"
+ autoCapitalize="none"
+ autoCorrect={false}
+ maxLength={1024}
+ returnKeyType="go"
+ editable={!busy}
+ onSubmitEditing={() => void passwordSignIn(step.found)}
+ />
+
setStep({ kind: 'sign-in', invitation: step.invitation })}
+ onPress={() => setFingerprintShown(!fingerprintShown)}
/>
+ {fingerprintShown ? (
+
+ ) : null}
+ {errorText}
setStep({ kind: 'address' })}
+ busy={busy}
+ disabled={busy || username.trim() === '' || password === ''}
+ onPress={() => void passwordSignIn(step.found)}
/>
>
) : step.kind === 'switch' ? (
diff --git a/apps/mobile/src/features/environments/pairing-strings.ts b/apps/mobile/src/features/environments/pairing-strings.ts
index a230f92594..bcd108c72b 100644
--- a/apps/mobile/src/features/environments/pairing-strings.ts
+++ b/apps/mobile/src/features/environments/pairing-strings.ts
@@ -3,6 +3,11 @@ import type { PairingFailure } from '@botharness/host-client/pairing';
export const en = {
pairTitle: 'Pair with your computer',
+ ownerSignIn: {
+ disabled: 'Password sign-in is turned off on this Host.',
+ alreadyPaired: 'This Host is already on this phone.',
+ credentialsInvalid: 'Check your username and password, then try again.',
+ },
allowCamera: 'Allow the camera to scan',
pairImage: {
choose: 'Choose QR image',
@@ -17,8 +22,9 @@ export const en = {
url: 'https://tobs.app/en/docs/mobile-pairing/',
linkError: 'Could not open the guide. Try again.',
},
- pasteLink: 'Or paste the pairing link',
- pasteLinkHint: 'In the code window on your computer, choose Copy pairing link.',
+ pasteLink: 'Or paste a link or Host address',
+ pasteLinkPlaceholder: 'Pairing link, invitation or https://…',
+ pairContinue: 'Connect',
pair: 'Pair',
pairAccount: {
title: `${productName.en} account`,
@@ -71,7 +77,6 @@ export const en = {
},
pairChoice: {
private: 'Private connection',
- privateDetail: 'Recommended. No account or Docker needed.',
privateHint:
'Turn on Private connection on your computer first. It publishes only the encrypted phone channel, and you approve this phone there.',
privatePath: [
@@ -85,12 +90,9 @@ export const en = {
account: `Sign in with a ${productName.en} account`,
accountDetail: 'Pick a computer on your account.',
lan: 'Use the same Wi-Fi',
- lanDetail: 'Scan a code. No account needed.',
- team: 'Join as a member',
- teamDetail: "Sign in to someone else's Host with an invitation or your username.",
tailscale: 'Use Tailscale',
- tailscaleDetail: 'Connect across networks.',
tailscaleHint: 'Sign in to the same Tailscale account on both devices.',
+ connectPath: ['Settings', 'Connections', 'Add connection', 'Connect a device to this Host'],
onComputer: 'On your computer',
lanPath: [
'Settings',
@@ -189,6 +191,11 @@ export const en = {
export const zh: typeof en = {
pairTitle: '与电脑配对',
+ ownerSignIn: {
+ disabled: '此 Host 已关闭账密登录。',
+ alreadyPaired: '这台手机已添加此 Host。',
+ credentialsInvalid: '检查用户名和密码后重试。',
+ },
allowCamera: '允许使用相机扫码',
pairImage: {
choose: '从相册选择二维码',
@@ -202,8 +209,9 @@ export const zh: typeof en = {
url: 'https://tobs.app/docs/mobile-pairing/',
linkError: '打开教程失败,再试一次。',
},
- pasteLink: '或粘贴配对链接',
- pasteLinkHint: '在电脑的二维码窗口点「复制配对链接」。',
+ pasteLink: '或粘贴链接、输入 Host 地址',
+ pasteLinkPlaceholder: '配对链接、邀请链接或 https://…',
+ pairContinue: '连接',
pair: '配对',
pairAccount: {
computers: '环境',
@@ -256,19 +264,15 @@ export const zh: typeof en = {
},
pairChoice: {
private: '私有连接',
- privateDetail: '推荐。不需要账号或 Docker。',
privateHint: '先在电脑上开启私有连接。它只公开加密的手机通道,并需要你在电脑上批准这台手机。',
privatePath: ['设置', '连接', '添加连接', '让设备连接本机', '私有连接(推荐)'],
needs: `电脑上需要安装 DSH(DeepSeek Harness)和 ${productName.zh} 插件。`,
account: `登录 ${productName.zh} 账号`,
accountDetail: '选择账号下的电脑。',
lan: '使用同一 Wi-Fi',
- lanDetail: '扫码即连,不需要账号。',
- team: '以成员身份加入',
- teamDetail: '用邀请或你的用户名登录他人的 Host。',
tailscale: '使用 Tailscale',
- tailscaleDetail: '跨网络连接。',
tailscaleHint: '两台设备登录同一个 Tailscale 账号。',
+ connectPath: ['设置', '连接', '添加连接', '让设备连接本机'],
onComputer: '在电脑上',
lanPath: ['设置', '连接', '添加连接', '让设备连接本机', '局域网'],
tailscalePath: ['设置', '连接', '添加连接', '让设备连接本机', 'Tailscale'],
diff --git a/apps/mobile/src/features/team/strings.ts b/apps/mobile/src/features/team/strings.ts
index 2b8355ea88..054458c178 100644
--- a/apps/mobile/src/features/team/strings.ts
+++ b/apps/mobile/src/features/team/strings.ts
@@ -30,6 +30,20 @@ export const en = {
fingerprintHint:
"Ask the Host owner to read out this Host's fingerprint, or compare it with the one in their Team settings. Continue only if every group matches.",
fingerprintMatches: 'Fingerprint matches',
+ hostTitle: 'Sign in to a Host',
+ connecting: 'Connecting…',
+ connectTo: 'Connect to {host}',
+ choosePassword: 'Sign in with username and password',
+ choosePasswordDetail: 'No approval on the computer. For the Owner and members.',
+ chooseApprove: 'Approve on the computer',
+ chooseApproveDetail: 'Scan a pairing code, then compare fingerprints.',
+ approveHint:
+ 'Open a pairing code on the computer and scan it. You then compare fingerprints and approve this phone on the computer.',
+ showFingerprint: 'View Host fingerprint',
+ hideFingerprint: 'Hide Host fingerprint',
+ needsCode:
+ 'This Host does not accept password sign-in. Show a pairing code on its computer and scan it.',
+ scanCode: 'Scan a pairing code',
switchAccount: 'Switch account',
switchHint: 'Sign in to this Host with another member account.',
signOut: 'Sign out',
@@ -69,6 +83,7 @@ export const en = {
mismatch: 'Passwords do not match.',
unreachable: 'Could not reach the Host. Check the network and try again.',
'storage-failed': 'Could not save the sign-in on this phone. Try again.',
+ 'host-update-required': 'Update this Host before signing in with a password.',
} as Record,
},
};
@@ -103,6 +118,18 @@ export const zh: typeof en = {
fingerprintHint:
'请 Host 所有者读出这台 Host 的指纹,或与其 Team 设置中显示的指纹对照。每一组都一致时再继续。',
fingerprintMatches: '指纹一致',
+ hostTitle: '登录 Host',
+ connecting: '正在连接…',
+ connectTo: '连接到 {host}',
+ choosePassword: '用用户名和密码登录',
+ choosePasswordDetail: '无需在电脑上确认,适用于 Owner 和成员。',
+ chooseApprove: '在电脑上批准',
+ chooseApproveDetail: '扫描配对码,再核对指纹。',
+ approveHint: '在电脑上打开配对码并扫码,然后核对指纹,在电脑上批准这台手机。',
+ showFingerprint: '查看 Host 指纹',
+ hideFingerprint: '收起 Host 指纹',
+ needsCode: '这台 Host 未开启账密登录。在它的电脑上打开配对码,然后扫码连接。',
+ scanCode: '扫描配对码',
switchAccount: '切换账号',
switchHint: '用另一个成员账号登录这个 Host。',
signOut: '退出登录',
@@ -138,6 +165,7 @@ export const zh: typeof en = {
mismatch: '两次输入的密码不一致。',
unreachable: '无法连接 Host,检查网络后再试。',
'storage-failed': '无法在本机保存登录,再试一次。',
+ 'host-update-required': '先更新这台 Host,再用账密登录。',
} as Record,
},
};
diff --git a/apps/mobile/src/host/connect-input.ts b/apps/mobile/src/host/connect-input.ts
new file mode 100644
index 0000000000..ca56e3dc37
--- /dev/null
+++ b/apps/mobile/src/host/connect-input.ts
@@ -0,0 +1,19 @@
+import { teamInvitationRoute } from '../team/team-link-path';
+
+export type ConnectInput =
+ | { kind: 'pairing'; text: string }
+ | { kind: 'invitation'; path: string }
+ | { kind: 'address'; address: string };
+
+const APP_LINK = /^deepseekbot(?:-dev)?:/iu;
+const ADDRESS =
+ /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:localhost|[^\s/:@?#]+\.[^\s/:@?#]+|\[[0-9a-f:]+\])(?::\d+)?\/?$/iu;
+
+export function connectInput(raw: string): ConnectInput {
+ const text = raw.trim();
+ const invitation = teamInvitationRoute(text);
+ if (invitation !== undefined) return { kind: 'invitation', path: invitation };
+ if (!APP_LINK.test(text) && ADDRESS.test(text))
+ return { kind: 'address', address: text.replace(/\/$/u, '') };
+ return { kind: 'pairing', text };
+}
diff --git a/apps/mobile/src/host/host-session.ts b/apps/mobile/src/host/host-session.ts
index bee9fc98be..fde2e767fb 100644
--- a/apps/mobile/src/host/host-session.ts
+++ b/apps/mobile/src/host/host-session.ts
@@ -42,6 +42,11 @@ import { nativeNotifications } from './native-notifications';
import { notificationAvatars } from './native-notification-avatars';
import { avatarInputs } from './notification-avatars';
import { revokePairing } from '@botharness/host-client/pairing';
+import type { OwnerSignInOptions } from '@botharness/host-client/owner-sign-in';
+import {
+ signInWithPassword,
+ type PasswordSignInError,
+} from '@botharness/host-client/password-sign-in';
import { createHostPush, type PushDelivery } from '@botharness/host-client/push';
import { createPushSession, type PushStatus } from './push-session';
import { notificationPreferences } from './native-notification-preferences';
@@ -641,6 +646,55 @@ export const hostSession = {
feeds.find((host) => host.saved.hostId === hostId),
getSelectionRevision: (): number => selectionIntent,
getSourceChangeRevision: (): number => sourceChangeRevision,
+ async signInPassword(
+ input: Pick & {
+ signal: AbortSignal;
+ },
+ ): Promise<
+ TeamResult
+ > {
+ let previous: SavedHost[];
+ try {
+ previous = await serialize(async () => stored.hosts);
+ } catch {
+ return { ok: false, code: 'storage-failed' };
+ }
+ const carrier = nativeCarrier();
+ const signed = await signInWithPassword({
+ ...input,
+ carrier,
+ previous: (id, route) =>
+ previous.find((host) => host.routes.includes(route)) ??
+ previous.find((host) => host.hostId === id),
+ allowExisting: (saved) => saved.member !== undefined,
+ });
+ if (!signed.ok || signed.value.role === 'member') return signed;
+
+ const { role: _role, ...host } = signed.value;
+ let saved = false;
+ try {
+ return await serialize(async () => {
+ if (input.signal.aborted) return { ok: false, code: 'request-cancelled' };
+ if (
+ stored.hosts.some(
+ (item) => item.hostId === host.hostId || item.routes.includes(input.route),
+ )
+ )
+ return { ok: false, code: 'already-paired' };
+ const intent = ++selectionIntent;
+ sourceChangeRevision++;
+ const current = () => !input.signal.aborted && intent === selectionIntent;
+ saved = await commit(withHost(stored, host), 'pair', current);
+ if (!saved) return { ok: false, code: 'request-cancelled' };
+ void pushSession.enable(stored.hosts);
+ return signed;
+ });
+ } catch {
+ return { ok: false, code: 'storage-failed' };
+ } finally {
+ if (!saved) void revokePairing({ host, carrier }).catch(() => undefined);
+ }
+ },
async pair(host: SavedHost, options: { confirmedIdentitySwitch?: boolean } = {}): Promise {
selectionIntent++;
if (state.saved?.hostId !== host.hostId) sourceChangeRevision++;
diff --git a/apps/mobile/src/host/native-carrier.ts b/apps/mobile/src/host/native-carrier.ts
index 1c1f79a99e..b382970ae5 100644
--- a/apps/mobile/src/host/native-carrier.ts
+++ b/apps/mobile/src/host/native-carrier.ts
@@ -2,6 +2,7 @@ import { installedAppVersion } from './app-version';
import { noiseKeyAgreement } from './noise-key-agreement';
import { requireOptionalNativeModule } from 'expo';
import { getRandomBytes } from 'expo-crypto';
+import { fetch as expoFetch } from 'expo/fetch';
import type { HostCarrier } from '@botharness/host-protocol/carrier';
import { isLanRoute } from '@botharness/host-protocol/route';
import { localNetworkStatus, openLanSocket } from './native-lan-socket';
@@ -51,10 +52,12 @@ export function nativeCarrier(): HostCarrier {
: {}),
async request(url, init) {
if (isLanRoute(new URL(url).origin)) throw new Error('encrypted-channel-required');
- const response = await fetch(url, {
+ const request = init.redirect === 'error' ? expoFetch : fetch;
+ const response = await request(url, {
method: init.method,
signal: init.signal,
credentials: 'omit',
+ ...(init.redirect === undefined ? {} : { redirect: init.redirect }),
headers: {
...(typeof init.body === 'string' ? { 'content-type': 'application/json' } : {}),
...init.headers,
diff --git a/apps/mobile/src/ui/shell/pair-scanner.tsx b/apps/mobile/src/ui/shell/pair-scanner.tsx
new file mode 100644
index 0000000000..36d35b23e5
--- /dev/null
+++ b/apps/mobile/src/ui/shell/pair-scanner.tsx
@@ -0,0 +1,245 @@
+import { CameraView, useCameraPermissions } from 'expo-camera';
+import { useFocusEffect, useRouter } from 'expo-router';
+import { useCallback, useRef, useState } from 'react';
+import { Pressable, View, useWindowDimensions } from 'react-native';
+
+import { connectInput } from '../../host/connect-input';
+import { readPairingImage, type PairingImageResult } from '../../host/pairing-image';
+import type { PairingMethod } from '@botharness/host-client/telemetry/schema';
+import { HOST_NAME_MAX } from '@botharness/host-client/ui/design/host-look';
+import { useDesignTheme } from '../design/theme';
+import { pairingScan, radius, space } from '../design/tokens';
+import { clearsPastedLink } from '../pairing-failure';
+import { Button } from '../primitives/button';
+import { ConnectionNameField } from '../primitives/connection-name-field';
+import { KeyboardFormScroll } from '../primitives/keyboard-form';
+import { labelInField } from '../primitives/field-label';
+import { Text } from '../primitives/text';
+import { TextField } from '../primitives/text-field';
+import { useStrings } from '../strings';
+import { DesktopPath } from './desktop-path';
+import { PairingFailureNotice } from './pairing-failure-notice';
+import { PairingVerification } from './pairing-verification';
+import { usePairing } from './use-pairing';
+
+export function PairScanner({
+ steps,
+ deepLink,
+ header,
+ children,
+}: {
+ steps: readonly string[];
+ deepLink?: string;
+ header?: React.ReactNode;
+ children?: React.ReactNode;
+}) {
+ const t = useStrings();
+ const theme = useDesignTheme();
+ const router = useRouter();
+ const { width } = useWindowDimensions();
+ const scan = Math.min(width * pairingScan.widthRatio, pairingScan.maxSize);
+ const [permission, requestPermission] = useCameraPermissions();
+ const [link, setLink] = useState('');
+ const [focused, setFocused] = useState(false);
+ const [readingImage, setReadingImage] = useState(false);
+ const [imageError, setImageError] =
+ useState['code']>();
+ const imageOperation = useRef(undefined);
+ const active = useRef(false);
+ const submitting = useRef(false);
+ const deepLinked = useRef(false);
+ const pairing = usePairing();
+
+ const pair = async (text: string, method: PairingMethod): Promise => {
+ if (!active.current || imageOperation.current || submitting.current) return;
+ const input = connectInput(text);
+ if (input.kind === 'invitation') {
+ setLink('');
+ router.push(input.path);
+ return;
+ }
+ if (input.kind === 'address') {
+ router.push({ pathname: '/pair/team', params: { address: input.address } });
+ return;
+ }
+ submitting.current = true;
+ setImageError(undefined);
+ try {
+ const failure = await pairing.pair(input.text, method);
+ if (active.current && failure !== undefined && clearsPastedLink(failure, method)) setLink('');
+ } finally {
+ submitting.current = false;
+ }
+ };
+
+ const chooseImage = async (): Promise => {
+ if (!active.current || imageOperation.current || submitting.current || pairing.busy) return;
+ const operation = new AbortController();
+ imageOperation.current = operation;
+ setReadingImage(true);
+ setImageError(undefined);
+ const result = await readPairingImage(operation.signal);
+ if (operation.signal.aborted || imageOperation.current !== operation) return;
+ imageOperation.current = undefined;
+ setReadingImage(false);
+ if (result.kind === 'error') setImageError(result.code);
+ else if (result.kind === 'link') {
+ pairing.forget();
+ await pair(result.link, 'image');
+ }
+ };
+
+ const retry = async (): Promise => {
+ if (!active.current || imageOperation.current || submitting.current) return;
+ submitting.current = true;
+ try {
+ await pairing.retry();
+ } finally {
+ submitting.current = false;
+ }
+ };
+
+ useFocusEffect(
+ useCallback(() => {
+ active.current = true;
+ setFocused(true);
+ if (deepLink !== undefined && !deepLinked.current) {
+ deepLinked.current = true;
+ void pair(`deepseekbot://pair?p=${deepLink}`, 'deep_link');
+ }
+ return () => {
+ active.current = false;
+ imageOperation.current?.abort();
+ imageOperation.current = undefined;
+ setReadingImage(false);
+ setFocused(false);
+ pairing.abort();
+ };
+ }, [deepLink]),
+ );
+
+ if (pairing.busy) return ;
+
+ return (
+
+ {header}
+
+
+
+ {permission?.granted ? (
+ focused &&
+ !readingImage && (
+ void pair(data, 'qr')}
+ />
+ )
+ ) : (
+ void requestPermission()}
+ accessibilityRole="button"
+ style={{
+ padding: space.x5,
+ minHeight: theme.touch,
+ justifyContent: 'center',
+ }}
+ >
+
+ {t.allowCamera}
+
+
+ )}
+
+ void chooseImage()}
+ />
+
+ {imageError !== undefined ? (
+
+ {t.pairImage[imageError]}
+
+ ) : pairing.error !== undefined ? (
+
+ ) : null}
+ {pairing.canRetry && imageError === undefined ? (
+ void retry()} />
+ ) : null}
+
+ {labelInField ? null : (
+
+ {t.pasteLink}
+
+ )}
+ {
+ setLink(value);
+ setImageError(undefined);
+ pairing.forget();
+ }}
+ placeholder={t.pasteLinkPlaceholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ returnKeyType="go"
+ editable={!readingImage}
+ onSubmitEditing={() => void pair(link, 'paste')}
+ />
+
+ {link.trim() !== '' && connectInput(link).kind === 'pairing' ? (
+
+ ) : null}
+ void pair(link, 'paste')}
+ />
+ {children}
+
+ );
+}
diff --git a/apps/mobile/test/connect-input.test.ts b/apps/mobile/test/connect-input.test.ts
new file mode 100644
index 0000000000..4d2114bd81
--- /dev/null
+++ b/apps/mobile/test/connect-input.test.ts
@@ -0,0 +1,40 @@
+import { expect, it } from 'vitest';
+
+import { connectInput } from '../src/host/connect-input';
+
+it('routes an invitation link to member sign-in', () => {
+ expect(connectInput(' deepseekbot://team?i=abc_123 ')).toEqual({
+ kind: 'invitation',
+ path: '/pair/team?i=abc_123',
+ });
+});
+
+it('keeps pairing links and unknown text on the pairing path', () => {
+ expect(connectInput('deepseekbot://pair?p=abc')).toEqual({
+ kind: 'pairing',
+ text: 'deepseekbot://pair?p=abc',
+ });
+ expect(connectInput('deepseekbot-dev://pair?p=abc').kind).toBe('pairing');
+ expect(connectInput('not a link').kind).toBe('pairing');
+ expect(connectInput('studio').kind).toBe('pairing');
+});
+
+it('treats a Host origin, with or without a scheme, as an address', () => {
+ for (const input of [
+ 'studio.example',
+ 'https://studio.example',
+ 'https://studio.example/',
+ 'http://studio.example',
+ 'studio.tailnet.ts.net:8443',
+ 'localhost:3000',
+ ])
+ expect(connectInput(input)).toEqual({
+ kind: 'address',
+ address: input.replace(/\/$/u, ''),
+ });
+});
+
+it('does not treat a URL with a path or query as a Host address', () => {
+ expect(connectInput('https://studio.example/pair?p=abc').kind).toBe('pairing');
+ expect(connectInput('https://user@studio.example').kind).toBe('pairing');
+});
diff --git a/apps/mobile/test/host-drawer.test.ts b/apps/mobile/test/host-drawer.test.ts
index e1c897072d..239b5b9604 100644
--- a/apps/mobile/test/host-drawer.test.ts
+++ b/apps/mobile/test/host-drawer.test.ts
@@ -123,6 +123,20 @@ describe('Host drawer', () => {
expect(drawer.getSnapshot()).toEqual({ open: true, shown: true });
});
+ it('closes and opens the shared Pair menu from Add computer', () => {
+ const pair = vi.fn();
+ const drawer = createHostDrawer({
+ showView: vi.fn(),
+ switchTo: vi.fn(async () => true),
+ pair,
+ notifications: vi.fn(),
+ });
+ drawer.open();
+ drawer.pairNew();
+ expect(drawer.getSnapshot().open).toBe(false);
+ expect(pair).toHaveBeenCalledTimes(1);
+ });
+
it('switches to the chosen Host and closes', async () => {
const switchTo = vi.fn(async () => true);
const drawer = createHostDrawer({
diff --git a/apps/mobile/test/host-session-multiple.test.ts b/apps/mobile/test/host-session-multiple.test.ts
index 0a4a7b56a1..ec8126c30b 100644
--- a/apps/mobile/test/host-session-multiple.test.ts
+++ b/apps/mobile/test/host-session-multiple.test.ts
@@ -8,6 +8,10 @@ import {
preferenceRetry,
} from './host-session-fixture';
import { FakeHost } from '../../../packages/host-client/test/fake-host.js';
+import type { signInWithPassword } from '@botharness/host-client/password-sign-in';
+
+const passwordSignIn = vi.hoisted(() => vi.fn());
+vi.mock('@botharness/host-client/password-sign-in', () => ({ signInWithPassword: passwordSignIn }));
vi.mock('expo-router', () => ({ useFocusEffect: () => undefined }));
vi.mock('react-native', () => ({
AppState: {
@@ -125,3 +129,85 @@ it('revokes the replaced member grant on the Host after a confirmed identity swi
expect(host.requests).toContain('POST https://m.tailnet.ts.net/botharness-device/unpair'),
);
});
+
+it('keeps existing Hosts and commits only one grant from concurrent Owner sign-ins', async () => {
+ const existing = new FakeHost('existing');
+ const target = new FakeHost('target');
+ remotes.set('existing.tailnet.ts.net', existing);
+ remotes.set('target.tailnet.ts.net', target);
+ const firstHost = {
+ hostId: 'existing',
+ hostName: 'Existing Host',
+ routes: ['https://existing.tailnet.ts.net'],
+ deviceId: 'existing-device',
+ credential: existing.credential,
+ };
+ const targetHost = {
+ hostId: 'target',
+ hostName: 'Target Host',
+ routes: ['https://target.tailnet.ts.net'],
+ deviceId: 'first-owner-device',
+ credential: target.credential,
+ };
+ session = (await import('../src/host/host-session')).hostSession;
+ await session.pair(firstHost);
+ const existingClient = session.getHost(firstHost.hostId)?.client;
+ const first = Promise.withResolvers>>();
+ passwordSignIn.mockReturnValueOnce(first.promise);
+ const second = Promise.withResolvers>>();
+ passwordSignIn.mockReturnValueOnce(second.promise);
+ const input = {
+ route: 'https://target.tailnet.ts.net',
+ username: 'owner',
+ password: 'test-password',
+ deviceName: 'Test phone',
+ signal: new AbortController().signal,
+ };
+ const original = session.signInPassword(input);
+ const competing = session.signInPassword(input);
+ await vi.waitFor(() => expect(passwordSignIn).toHaveBeenCalledTimes(2));
+ first.resolve({ ok: true, value: { ...targetHost, role: 'owner' } });
+ expect(await original).toEqual({ ok: true, value: { ...targetHost, role: 'owner' } });
+ second.resolve({
+ ok: true,
+ value: {
+ ...targetHost,
+ deviceId: 'second-owner-device',
+ credential: 'new-grant',
+ role: 'owner',
+ },
+ });
+ expect(await competing).toEqual({ ok: false, code: 'already-paired' });
+ expect(session.getState().hosts).toEqual([firstHost, targetHost]);
+ expect(session.getHost(firstHost.hostId)?.client).toBe(existingClient);
+ expect(session.getState().saved).toEqual(targetHost);
+});
+
+it('returns a member grant from password sign-in without saving it', async () => {
+ session = (await import('../src/host/host-session')).hostSession;
+ const member = {
+ hostId: 'team',
+ hostName: 'Team Host',
+ routes: ['https://team.tailnet.ts.net'],
+ deviceId: 'member-device',
+ credential: 'member-device.secret',
+ member: {
+ humanId: 'h1',
+ username: 'ada',
+ displayName: 'Ada',
+ fingerprint: 'abcd',
+ mustChangePassword: true,
+ },
+ role: 'member' as const,
+ };
+ passwordSignIn.mockResolvedValueOnce({ ok: true, value: member });
+ const result = await session.signInPassword({
+ route: 'https://team.tailnet.ts.net',
+ username: 'ada',
+ password: 'one-time-password',
+ deviceName: 'Test phone',
+ signal: new AbortController().signal,
+ });
+ expect(result).toEqual({ ok: true, value: member });
+ expect(session.getState().hosts.some((host) => host.hostId === 'team')).toBe(false);
+});
diff --git a/apps/mobile/test/native-carrier-request.test.ts b/apps/mobile/test/native-carrier-request.test.ts
new file mode 100644
index 0000000000..26c285f92f
--- /dev/null
+++ b/apps/mobile/test/native-carrier-request.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, expect, it, vi } from 'vitest';
+
+const expoFetch = vi.hoisted(() => vi.fn());
+
+vi.mock('expo', () => ({ requireOptionalNativeModule: () => null }));
+vi.mock('expo-crypto', () => ({ getRandomBytes: () => new Uint8Array(32) }));
+vi.mock('expo/fetch', () => ({ fetch: expoFetch }));
+vi.mock('../src/host/app-version', () => ({ installedAppVersion: () => undefined }));
+vi.mock('../src/host/noise-key-agreement', () => ({ noiseKeyAgreement: undefined }));
+vi.mock('../src/host/native-lan-socket', () => ({
+ localNetworkStatus: () => 'unknown',
+ openLanSocket: vi.fn(),
+}));
+
+import { nativeCarrier } from '../src/host/native-carrier';
+
+afterEach(() => {
+ expoFetch.mockReset();
+ vi.unstubAllGlobals();
+});
+
+it('sends strict Host discovery through Expo fetch without redirects or cookies', async () => {
+ const globalFetch = vi.fn();
+ vi.stubGlobal('fetch', globalFetch);
+ expoFetch.mockRejectedValueOnce(new Error('redirect refused'));
+ const url = 'https://host.example/botharness-device/channel';
+ const signal = new AbortController().signal;
+
+ await expect(
+ nativeCarrier().request(url, { method: 'GET', redirect: 'error', signal }),
+ ).rejects.toThrow('redirect refused');
+ expect(expoFetch).toHaveBeenCalledExactlyOnceWith(url, {
+ method: 'GET',
+ signal,
+ credentials: 'omit',
+ redirect: 'error',
+ headers: {},
+ });
+ expect(globalFetch).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/test/pair-choice.test.tsx b/apps/mobile/test/pair-choice.test.tsx
index 1f191792cc..19e68e1cd3 100644
--- a/apps/mobile/test/pair-choice.test.tsx
+++ b/apps/mobile/test/pair-choice.test.tsx
@@ -9,9 +9,19 @@ vi.mock('react-native-safe-area-context', () => ({
}));
vi.mock('react-native', () => import('./react-native-shim'));
vi.mock('react-native-svg', () => ({ default: () => null, Circle: () => null, Path: () => null }));
-vi.mock('../src/ui/primitives/row-icon', () => ({ RowIcon: () => null }));
+vi.mock('../src/ui/primitives/row-icon', async () => {
+ const { createElement } = await import('react');
+ return { RowIcon: ({ name }: { name: string }) => createElement('i', { 'data-icon': name }) };
+});
vi.mock('../src/ui/chat/sheet', () => ({ SHEET_GROUP: 'sheet' }));
vi.mock('../src/host/host-session', () => ({ useHostSession: () => ({ hosts: [] }) }));
+vi.mock('../src/ui/shell/pair-scanner', async () => {
+ const { createElement } = await import('react');
+ return {
+ PairScanner: ({ steps, children }: { steps: string[]; children: React.ReactNode }) =>
+ createElement('section', { 'data-testid': 'pair-scanner' }, steps.join(' › '), children),
+ };
+});
const router = vi.hoisted(() => ({ push: vi.fn(), back: vi.fn(), dismissTo: vi.fn() }));
const params = vi.hoisted(() => ({ current: {} as Record }));
vi.mock('expo-router', () => ({
@@ -45,29 +55,21 @@ async function render(): Promise {
return host;
}
-it('offers LAN, account sign-in and Tailscale through the existing pairing flow', async () => {
+it('leaves only the scanner and Tobs account sign-in as ways to connect', async () => {
const view = await render();
- expect(view.textContent).toContain(t.pairChoice.account);
- expect(view.textContent).toContain(t.pairChoice.tailscale);
- expect(view.textContent).not.toContain(t.cloud.title);
- expect(view.querySelector('input')).toBeNull();
- expect(view.textContent).toContain(t.pairChoice.lan);
- await act(async () =>
- view.querySelector('[data-testid="pair-choice-lan"]')!.click(),
+ expect(view.querySelector('[data-testid="pair-scanner"]')?.textContent).toContain(
+ t.pairChoice.connectPath.join(' › '),
);
- expect(router.push).toHaveBeenLastCalledWith({
- pathname: '/pair/tailscale',
- params: { mode: 'lan' },
- });
-
+ const rows = [...view.querySelectorAll('[data-testid^="pair-"]')]
+ .map((row) => row.dataset.testid)
+ .filter((id) => id !== 'pair-scanner');
+ expect(rows).toEqual(['pair-choice-account', 'pair-guide-open']);
+ expect(view.textContent).not.toContain(t.pairChoice.lan);
+ expect(view.textContent).not.toContain(t.cloud.title);
await act(async () =>
view.querySelector('[data-testid="pair-choice-account"]')!.click(),
);
expect(router.push).toHaveBeenLastCalledWith('/pair/account');
- await act(async () =>
- view.querySelector('[data-testid="pair-choice-tailscale"]')!.click(),
- );
- expect(router.push).toHaveBeenLastCalledWith('/pair/tailscale');
});
it('forwards a pairing link to Tailscale and an account computer to sign-in', async () => {
@@ -85,11 +87,13 @@ it('forwards a pairing link to Tailscale and an account computer to sign-in', as
});
});
-it('states what the computer needs and opens the setup guide', async () => {
+it('puts what the computer needs on the setup guide row and opens the guide', async () => {
const { Linking } = await import('react-native');
const openURL = vi.spyOn(Linking, 'openURL').mockResolvedValue(undefined);
const view = await render();
- expect(view.textContent).toContain(t.pairChoice.needs);
+ expect(view.querySelector('[data-testid="pair-guide-open"]')?.textContent).toContain(
+ t.pairChoice.needs,
+ );
await act(async () =>
view.querySelector('[data-testid="pair-guide-open"]')!.click(),
);
diff --git a/apps/mobile/test/pair-image.test.tsx b/apps/mobile/test/pair-image.test.tsx
index aad2a8fdd3..6572834e97 100644
--- a/apps/mobile/test/pair-image.test.tsx
+++ b/apps/mobile/test/pair-image.test.tsx
@@ -28,7 +28,9 @@ vi.mock('expo-application', () => ({
vi.mock('expo-device', () => ({ osVersion: '18.2' }));
vi.mock('expo-clipboard', () => ({ setStringAsync: vi.fn(async () => true) }));
vi.mock('expo-image-picker', () => ({ launchImageLibraryAsync: native.pick }));
+const router = vi.hoisted(() => ({ push: vi.fn() }));
vi.mock('expo-router', () => ({
+ useRouter: () => router,
Stack: { Screen: () => null },
useLocalSearchParams: () => ({}),
useFocusEffect: (focus: () => () => void) => {
@@ -174,3 +176,51 @@ it('shows the computer menu path for Tailscale instead of a paragraph', async ()
for (const step of t.pairChoice.tailscalePath) expect(path.textContent).toContain(step);
expect(host.textContent).toContain(t.pairChoice.tailscaleHint);
});
+
+it('opens member sign-in when the chosen image holds an invitation', async () => {
+ native.scan.mockResolvedValue([{ data: 'deepseekbot://team?i=invite_1' }]);
+ await choose();
+ expect(router.push).toHaveBeenCalledExactlyOnceWith('/pair/team?i=invite_1');
+ expect(pairing.pair).not.toHaveBeenCalled();
+});
+
+it('opens Host sign-in when a Host address is pasted', async () => {
+ await act(async () => root!.render());
+ await act(async () => {
+ navigation.blur = navigation.focus!();
+ });
+ const input = host.querySelector('[data-testid="pair-link-input"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(input, 'studio.example');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () =>
+ host.querySelector('[data-testid="pair-link-submit"]')!.click(),
+ );
+ expect(router.push).toHaveBeenCalledExactlyOnceWith({
+ pathname: '/pair/team',
+ params: { address: 'studio.example' },
+ });
+ expect(pairing.pair).not.toHaveBeenCalled();
+});
+
+it('asks for a name on this phone only after a pairing link is pasted', async () => {
+ await act(async () => root!.render());
+ await act(async () => {
+ navigation.blur = navigation.focus!();
+ });
+ const named = () => host.querySelector(`[aria-label="${t.connectionName}"]`) !== null;
+ const input = host.querySelector('[data-testid="pair-link-input"]')!;
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;
+ const type = (value: string) =>
+ act(async () => {
+ setter.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ expect(named()).toBe(false);
+ await type('studio.example');
+ expect(named()).toBe(false);
+ await type('deepseekbot://pair?p=example');
+ expect(named()).toBe(true);
+});
diff --git a/apps/mobile/test/team-sign-in-switch.test.tsx b/apps/mobile/test/team-sign-in-switch.test.tsx
index 9fad537bb3..7854c027d2 100644
--- a/apps/mobile/test/team-sign-in-switch.test.tsx
+++ b/apps/mobile/test/team-sign-in-switch.test.tsx
@@ -15,12 +15,18 @@ vi.mock('react-native-svg', () => ({ default: () => null, Path: () => null, Circ
vi.mock('react-native-gesture-handler', () => import('./gesture-handler-shim'));
vi.mock('expo-symbols', () => ({ SymbolView: () => null }));
vi.mock('expo-constants', () => ({ default: { deviceName: 'Test phone' } }));
-const router = vi.hoisted(() => ({ dismissTo: vi.fn() }));
+const router = vi.hoisted(() => ({ dismissTo: vi.fn(), back: vi.fn() }));
const params = vi.hoisted(() => ({ value: { i: 'invite' } as Record }));
-vi.mock('expo-router', () => ({
- useRouter: () => router,
- useLocalSearchParams: () => params.value,
-}));
+vi.mock('expo-router', async () => {
+ const { useState } = await import('react');
+ return {
+ useRouter: () => router,
+ useLocalSearchParams: () => params.value,
+ useFocusEffect: (focus: () => void) => {
+ useState(() => queueMicrotask(focus));
+ },
+ };
+});
const bob = vi.hoisted(() => ({
hostId: 'h',
hostName: 'Studio',
@@ -37,6 +43,7 @@ const bob = vi.hoisted(() => ({
}));
const session = vi.hoisted(() => ({
getState: () => ({ hosts: [bob] }),
+ signInPassword: vi.fn(),
pairMember: vi.fn(async (_host: unknown, options?: { confirmedIdentitySwitch?: boolean }) =>
options?.confirmedIdentitySwitch
? { ok: true as const, value: bob }
@@ -45,6 +52,7 @@ const session = vi.hoisted(() => ({
}));
vi.mock('../src/host/host-session', () => ({ hostSession: session }));
vi.mock('../src/host/native-carrier', () => ({ nativeCarrier: () => ({}) }));
+vi.mock('../src/ui/chat/sheet', () => ({ SHEET_GROUP: 'sheet' }));
const revokePairing = vi.hoisted(() => vi.fn(async () => 'revoked' as const));
vi.mock('@botharness/host-client/pairing', () => ({ revokePairing }));
const dialog = vi.hoisted(() => vi.fn());
@@ -64,19 +72,16 @@ vi.mock('@botharness/host-client/team-client', () => ({
signInTeamDevice: signInTeamDevice,
changeTeamDevicePassword: vi.fn(),
}));
-const addressInvitation = vi.hoisted(() =>
- vi.fn(async (_input: unknown) => ({
- ok: true as const,
- value: {
- v: 1,
- host: { id: 'other-host', name: 'Studio', fingerprint: 'b'.repeat(64) },
- routes: ['https://studio.example'],
- username: 'dana',
- expiresAt: '2099-01-01T00:00:00Z',
- },
- })),
+const discovery = vi.hoisted(() => ({
+ route: 'https://studio.example',
+ host: { id: 'other-host', name: 'Studio', fingerprint: 'b'.repeat(64) },
+ publicKey: 'c'.repeat(64),
+ signIn: { password: true } as { password: boolean } | undefined,
+}));
+const discoverHostAddress = vi.hoisted(() =>
+ vi.fn(async (_input: unknown) => ({ ok: true as const, value: discovery })),
);
-vi.mock('@botharness/host-client/team-sign-in', () => ({ addressInvitation }));
+vi.mock('@botharness/host-client/password-sign-in', () => ({ discoverHostAddress }));
const landing = vi.hoisted(() => ({ filter: vi.fn(), closePage: vi.fn(() => true) }));
vi.mock('../src/host/native-conversation-filter', () => ({
conversationFilter: { set: landing.filter },
@@ -197,9 +202,8 @@ it('switches to another member account on a saved Host by username, behind the s
}
});
-it('signs in with a Host address and username after the fingerprint is confirmed', async () => {
- signInTeamDevice.mockClear();
- params.value = {};
+async function renderAddress(address: string) {
+ params.value = { address };
const element = document.createElement('div');
document.body.append(element);
const root = createRoot(element);
@@ -213,41 +217,121 @@ it('signs in with a Host address and username after the fingerprint is confirmed
};
const press = (id: string) =>
act(async () => element.querySelector(`[data-testid="${id}"]`)!.click());
+ await act(async () => root.render());
+ const close = () => {
+ act(() => root.unmount());
+ element.remove();
+ params.value = { i: 'invite' };
+ };
+ return { element, type, press, close };
+}
+
+it('asks how to connect, then signs in with one username and password form for an address', async () => {
+ router.dismissTo.mockClear();
+ session.signInPassword.mockResolvedValueOnce({
+ ok: true,
+ value: { ...bob, hostId: 'other-host', member: undefined, role: 'owner' },
+ });
+ const { element, type, press, close } = await renderAddress('studio.example');
try {
- await act(async () => root.render());
- await press('team-use-username');
- await type('team-address', 'studio.example');
- await type('team-username', 'Dana');
- await press('team-address-continue');
- expect(addressInvitation).toHaveBeenCalledWith(
- expect.objectContaining({ route: 'https://studio.example', username: 'dana' }),
+ expect(discoverHostAddress).toHaveBeenLastCalledWith(
+ expect.objectContaining({ input: 'studio.example' }),
);
+ expect(element.querySelector('[data-testid="team-password"]')).toBeNull();
+ expect(element.querySelector('[data-testid="team-choose-approve"]')).not.toBeNull();
+ await press('team-choose-password');
+ expect(element.querySelector('[data-testid="team-fingerprint-rows"]')).toBeNull();
+ await press('team-fingerprint-toggle');
const rows = element.querySelector('[data-testid="team-fingerprint-rows"]')!;
expect(Array.from(rows.children, (row) => row.textContent)).toEqual(
Array(4).fill('bbbb bbbb bbbb bbbb'),
);
- expect(element.querySelector('[data-testid="team-fingerprint-copy-state"]')?.textContent).toBe(
- t.fingerprintTapToCopy,
- );
await press('team-fingerprint');
expect(clipboard.setStringAsync).toHaveBeenCalledWith(Array(16).fill('bbbb').join(' '));
- expect(element.querySelector('[data-testid="team-fingerprint-copy-state"]')?.textContent).toBe(
- t.fingerprintCopied,
- );
- expect(element.querySelector('[data-testid="team-password"]')).toBeNull();
- await press('team-fingerprint-matches');
- await signIn(element);
- expect(signInTeamDevice).toHaveBeenCalledWith(
+ await type('team-username', 'Dana');
+ await type('team-password', 'owner-password');
+ await press('team-sign-in');
+ expect(session.signInPassword).toHaveBeenLastCalledWith(
expect.objectContaining({
- invitation: expect.objectContaining({
- username: 'dana',
- routes: ['https://studio.example'],
- }),
+ route: 'https://studio.example',
+ username: 'Dana',
+ password: 'owner-password',
}),
);
+ expect(session.pairMember).not.toHaveBeenCalledWith(
+ expect.objectContaining({ hostId: 'other-host' }),
+ undefined,
+ );
+ expect(router.dismissTo).toHaveBeenCalledWith('/');
} finally {
- act(() => root.unmount());
- element.remove();
- params.value = { i: 'invite' };
+ close();
+ }
+});
+
+it('continues a member to the password change after address sign-in', async () => {
+ session.signInPassword.mockResolvedValueOnce({
+ ok: true,
+ value: {
+ ...bob,
+ hostId: 'other-host',
+ member: { ...bob.member, mustChangePassword: true },
+ role: 'member',
+ },
+ });
+ const { element, type, press, close } = await renderAddress('https://studio.example');
+ try {
+ await press('team-choose-password');
+ await type('team-username', 'bob');
+ await type('team-password', 'one-time-password');
+ await press('team-sign-in');
+ expect(element.querySelector('[data-testid="team-new-password"]')).not.toBeNull();
+ } finally {
+ close();
+ }
+});
+
+it('guides a person who chooses computer approval to open and scan a pairing code', async () => {
+ router.back.mockClear();
+ const { element, press, close } = await renderAddress('studio.example');
+ try {
+ await press('team-choose-approve');
+ expect(element.textContent).toContain(t.teamSignIn.approveHint);
+ expect(element.querySelector('[data-testid="desktop-path"]')).not.toBeNull();
+ expect(element.querySelector('[data-testid="team-password"]')).toBeNull();
+ await press('team-scan-code');
+ expect(router.back).toHaveBeenCalledOnce();
+ } finally {
+ close();
+ }
+});
+
+it('sends a Host without password sign-in back to the scanner before asking for a password', async () => {
+ router.back.mockClear();
+ discovery.signIn = { password: false };
+ const { element, press, close } = await renderAddress('studio.example');
+ try {
+ expect(element.querySelector('[data-testid="team-password"]')).toBeNull();
+ expect(element.textContent).toContain(t.teamSignIn.needsCode);
+ await press('team-scan-code');
+ expect(router.back).toHaveBeenCalledOnce();
+ } finally {
+ discovery.signIn = { password: true };
+ close();
+ }
+});
+
+it('explains a refused address and keeps it for correction', async () => {
+ discoverHostAddress.mockResolvedValueOnce({
+ ok: false,
+ code: 'insecure-transport',
+ } as never);
+ const { element, close } = await renderAddress('http://studio.example');
+ try {
+ expect(element.textContent).toContain(t.teamSignIn.errors['insecure-transport']);
+ expect(element.querySelector('[data-testid="team-address"]')?.value).toBe(
+ 'http://studio.example',
+ );
+ } finally {
+ close();
}
});
diff --git a/changes/4900-mobile-owner-remote-sign-in.md b/changes/4900-mobile-owner-remote-sign-in.md
new file mode 100644
index 0000000000..cffd754816
--- /dev/null
+++ b/changes/4900-mobile-owner-remote-sign-in.md
@@ -0,0 +1,11 @@
+---
+section: Added
+---
+
+## en
+
+- iOS and Android can add a Host with its trusted HTTPS address and Owner credentials during initial setup or when adding another Host ([#4900](https://github.com/BotHarness/DeepSeekBot/issues/4900)).
+
+## zh
+
+- iOS 和 Android 支持用可信 HTTPS 地址和 Owner 账密连接 Host,首次连接或添加另一台 Host 时均可使用([#4900](https://github.com/BotHarness/DeepSeekBot/issues/4900))。
diff --git a/changes/4962-host-password-sign-in.md b/changes/4962-host-password-sign-in.md
new file mode 100644
index 0000000000..52cd8b5889
--- /dev/null
+++ b/changes/4962-host-password-sign-in.md
@@ -0,0 +1,11 @@
+---
+section: Added
+---
+
+## en
+
+- Hosts advertise password sign-in on HTTPS and can sign in Owners and Team members through one encrypted device flow. [#4962](https://github.com/BotHarness/DeepSeekBot/issues/4962)
+
+## zh
+
+- Host 可通过 HTTPS 告知客户端是否支持账密登录,Owner 和团队成员可使用同一套加密设备登录流程。 [#4962](https://github.com/BotHarness/DeepSeekBot/issues/4962)
diff --git a/changes/4962-mobile-connect-scan-or-address.md b/changes/4962-mobile-connect-scan-or-address.md
new file mode 100644
index 0000000000..795b9d8ac0
--- /dev/null
+++ b/changes/4962-mobile-connect-scan-or-address.md
@@ -0,0 +1,11 @@
+---
+section: Changed
+---
+
+## en
+
+- The iOS and Android Pair screen now has two ways in: scan or enter, and Tobs account sign-in. One field accepts a pairing link, an invitation link or a Host address. For an address, you choose between signing in with a username and password, where the Host decides whether you are its Owner or a member, and approving on the computer with a pairing code and fingerprints ([#4962](https://github.com/BotHarness/DeepSeekBot/issues/4962)).
+
+## zh
+
+- iOS 和 Android 的配对页只保留两条路:扫码或输入,以及登录 Tobs 账号。同一个输入框可以填配对链接、邀请链接或 Host 地址;输入地址后可选择用用户名和密码登录(由 Host 判断你是 Owner 还是成员),或在电脑上批准(扫配对码并核对指纹)([#4962](https://github.com/BotHarness/DeepSeekBot/issues/4962))。
diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md
index bb4aca6ec7..e31ae27dac 100644
--- a/docs/architecture/botharness-architecture.md
+++ b/docs/architecture/botharness-architecture.md
@@ -1593,6 +1593,8 @@ 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.
+HTTPS device discovery publishes one password sign-in capability bit from Team settings and active member credentials. After the Client verifies the Host key, the Noise gateway hands the unified password attempt to Team authentication, which applies its shared limiter and issues the existing Owner device credential or member device grant. The Client uses the role in the encrypted reply to save the grant and preserve the member's first-password change requirement. [Connection decision](../decisions/connections.md#remote-host-password-sign-in-uses-the-same-encrypted-device-channel-on-every-route)
+
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 5f471ebf0d..012df132e2 100644
--- a/docs/decisions/connections.md
+++ b/docs/decisions/connections.md
@@ -75,6 +75,8 @@ A Host sign-in link or QR code supplies the route and fingerprint for first cont
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.
+Clients connecting by HTTPS address read `signIn.password` from `GET /botharness-device/channel`. It is true when the Owner has enabled password sign-in or Team mode has an active member with a password credential. The Noise gateway accepts one unified password attempt per channel and resolves the role from the Host's credential store. An unknown username and a wrong password both perform an Argon2id verification and return the same refusal. A disabled Owner account returns a distinct refusal only after password verification. [#4962](https://github.com/BotHarness/DeepSeekBot/issues/4962)
+
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.
diff --git a/packages/client/src/client/owner-sign-in-dialog.tsx b/packages/client/src/client/owner-sign-in-dialog.tsx
index 0c10ece5dc..6c83ac9908 100644
--- a/packages/client/src/client/owner-sign-in-dialog.tsx
+++ b/packages/client/src/client/owner-sign-in-dialog.tsx
@@ -1,4 +1,5 @@
import { useRef, useState, type ReactElement } from 'react';
+import { ownerSignInOrigin } from '@botharness/host-client/owner-sign-in';
import { TextField } from './ds/field.js';
import { FormDialog } from './ds/form-dialog.js';
@@ -8,21 +9,6 @@ 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,
@@ -55,7 +41,7 @@ export function OwnerSignInDialog({
const mount = useMountedResource(() => () => pending.current?.abort(), []);
const submit = () => {
if (pending.current) return;
- const route = httpsOrigin(address.trim());
+ const route = ownerSignInOrigin(address);
if (!route) {
setError(t('teamSignIn.error.insecure-transport'));
return;
diff --git a/packages/connect-relay/src/relay-offers.ts b/packages/connect-relay/src/relay-offers.ts
index 7795ff8e2c..6d16a2cb2c 100644
--- a/packages/connect-relay/src/relay-offers.ts
+++ b/packages/connect-relay/src/relay-offers.ts
@@ -45,6 +45,7 @@ export function createOfferHandler({ options, now, touch, hostname }: OfferHandl
try {
reply = await (options.fetchHost ?? fetch)(`https://${hostname(row)}${OFFER_PATH}`, {
method: 'GET',
+ redirect: 'error',
signal: AbortSignal.timeout(OFFER_TIMEOUT_MS),
});
} catch (error) {
@@ -59,6 +60,7 @@ export function createOfferHandler({ options, now, touch, hostname }: OfferHandl
| {
encryption?: { protocol?: unknown; publicKey?: unknown };
host?: { id?: unknown; name?: unknown };
+ signIn?: { password?: unknown };
}
| undefined;
if (
@@ -80,6 +82,9 @@ export function createOfferHandler({ options, now, touch, hostname }: OfferHandl
expiresAt: new Date(now().getTime() + 5 * 60 * 1000).toISOString(),
hostname: hostname(row),
host: { id: answer.host.id, name: answer.host.name },
+ ...(typeof answer.signIn?.password === 'boolean'
+ ? { signIn: { password: answer.signIn.password } }
+ : {}),
});
};
}
diff --git a/packages/connect-relay/test/connect-relay.test.ts b/packages/connect-relay/test/connect-relay.test.ts
index 1765194a46..1e9d588d08 100644
--- a/packages/connect-relay/test/connect-relay.test.ts
+++ b/packages/connect-relay/test/connect-relay.test.ts
@@ -759,41 +759,55 @@ describe('Connect relay phone offers', () => {
return relay;
}
- it('returns signed enrollment metadata without asking the Host for an outer bearer offer', async () => {
- const seen: { url: string; method: string; body: unknown }[] = [];
- const encryption = { protocol: 'connect-noise-xk-v1', publicKey: 'ab'.repeat(32) };
- const { call, at } = await linked(async (input, init) => {
- seen.push({ url: String(input), method: init?.method ?? 'GET', body: init?.body });
- return Response.json({ host: { id: 'pairing-host-1', name: 'Studio Mac' }, encryption });
- });
- const tunnel = await call('POST', '/v1/hosts/haaaaaaaaaaab/tunnel', {
- as: 'user_alice',
- body: { originPort: 41001 },
- });
- const result = await call('POST', '/v1/hosts/haaaaaaaaaaab/offer', {
- as: 'user_alice',
- body: { verifierHash: VERIFIER_HASH, name: ' iPhone ' },
- });
- expect(result.status).toBe(200);
- expect(result.body).toMatchObject({ host: { id: 'pairing-host-1' }, encryption });
- expect(result.body['offer']).toBeUndefined();
- expect(seen).toEqual([
- {
- url: 'https://haaaaaaaaaaab.deepseekbot.dev/botharness-device/channel',
- method: 'GET',
- body: undefined,
- },
- ]);
- const enrollment = result.body['enrollment'] as { body: string; signature: string };
- expect(JSON.parse(enrollment.body)).toEqual({
- hostId: 'haaaaaaaaaaab',
- account: 'user_alice',
- verifierHash: VERIFIER_HASH,
- name: 'iPhone',
- issuedAt: at(),
- });
- expect(enrollment.signature).toBe(await hmac(tunnel.body['relayKey'], enrollment.body));
- });
+ it.each([true, false, undefined])(
+ 'returns signed enrollment metadata and forwards password availability %s',
+ async (password) => {
+ const seen: { url: string; method: string; body: unknown; redirect: unknown }[] = [];
+ const encryption = { protocol: 'connect-noise-xk-v1', publicKey: 'ab'.repeat(32) };
+ const { call, at } = await linked(async (input, init) => {
+ seen.push({
+ url: String(input),
+ method: init?.method ?? 'GET',
+ body: init?.body,
+ redirect: init?.redirect,
+ });
+ return Response.json({
+ host: { id: 'pairing-host-1', name: 'Studio Mac' },
+ encryption,
+ ...(password === undefined ? {} : { signIn: { password, ignored: 'extra' } }),
+ });
+ });
+ const tunnel = await call('POST', '/v1/hosts/haaaaaaaaaaab/tunnel', {
+ as: 'user_alice',
+ body: { originPort: 41001 },
+ });
+ const result = await call('POST', '/v1/hosts/haaaaaaaaaaab/offer', {
+ as: 'user_alice',
+ body: { verifierHash: VERIFIER_HASH, name: ' iPhone ' },
+ });
+ expect(result.status).toBe(200);
+ expect(result.body).toMatchObject({ host: { id: 'pairing-host-1' }, encryption });
+ expect(result.body['signIn']).toEqual(password === undefined ? undefined : { password });
+ expect(result.body['offer']).toBeUndefined();
+ expect(seen).toEqual([
+ {
+ url: 'https://haaaaaaaaaaab.deepseekbot.dev/botharness-device/channel',
+ method: 'GET',
+ body: undefined,
+ redirect: 'error',
+ },
+ ]);
+ const enrollment = result.body['enrollment'] as { body: string; signature: string };
+ expect(JSON.parse(enrollment.body)).toEqual({
+ hostId: 'haaaaaaaaaaab',
+ account: 'user_alice',
+ verifierHash: VERIFIER_HASH,
+ name: 'iPhone',
+ issuedAt: at(),
+ });
+ expect(enrollment.signature).toBe(await hmac(tunnel.body['relayKey'], enrollment.body));
+ },
+ );
it('authorizes a client-side attempt without probing an offline connector, scoped to the account', async () => {
const probe = vi.fn(async () => {
diff --git a/packages/core/src/devices/channel-discovery.ts b/packages/core/src/devices/channel-discovery.ts
new file mode 100644
index 0000000000..0ddbfce605
--- /dev/null
+++ b/packages/core/src/devices/channel-discovery.ts
@@ -0,0 +1,34 @@
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import type { EncryptionIdentity } from './noise-identity.js';
+import type { HostIdentity } from './pairing.js';
+
+export function createChannelDiscovery(options: {
+ host(): HostIdentity;
+ encryption(): Promise;
+ passwordSignInAvailable(): boolean;
+}) {
+ return async (request: IncomingMessage, response: ServerResponse): Promise => {
+ if (request.method !== 'GET') {
+ response.writeHead(405);
+ response.end();
+ return;
+ }
+ try {
+ const encryption = await options.encryption();
+ const signIn = { password: options.passwordSignInAvailable() };
+ const body = JSON.stringify({ host: options.host(), encryption, signIn });
+ response.writeHead(200, {
+ 'content-type': 'application/json',
+ 'cache-control': 'no-store',
+ 'access-control-allow-origin': '*',
+ });
+ response.end(body);
+ } catch {
+ response.writeHead(503, {
+ 'content-type': 'application/json',
+ 'cache-control': 'no-store',
+ });
+ response.end(JSON.stringify({ code: 'host-key-unavailable' }));
+ }
+ };
+}
diff --git a/packages/core/src/devices/encrypted-gateway.ts b/packages/core/src/devices/encrypted-gateway.ts
index 1cbee81bcf..2c34016ef2 100644
--- a/packages/core/src/devices/encrypted-gateway.ts
+++ b/packages/core/src/devices/encrypted-gateway.ts
@@ -156,7 +156,7 @@ export function createEncryptedGateway(options: {
closed = false,
admitted = false;
let channelHeaders: Record = {};
- let ownerSignInAttempted = false;
+ let signInAttempt: 'none' | 'team-sign-in' | 'owner-sign-in' | 'password-sign-in' = 'none';
let enrollmentOffer: { body: string; offer: string } | undefined;
let detach: (() => void) | undefined;
const streams = new Map();
@@ -646,17 +646,39 @@ export function createEncryptedGateway(options: {
const type = input['type'];
if (!admitted) {
const publicKey = Buffer.from(channel.peerKey()).toString('hex');
- if ((type === 'team-sign-in' || type === 'owner-sign-in') && options.memberDevices) {
+ if (
+ type === 'password-sign-in' ||
+ ((type === 'team-sign-in' || type === 'owner-sign-in') && options.memberDevices)
+ ) {
+ const passwordSignIn = type === 'password-sign-in';
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;
+ const reply = passwordSignIn
+ ? 'password-signed-in'
+ : ownerSignIn
+ ? 'owner-signed-in'
+ : 'team-signed-in';
+ if (
+ signInAttempt === 'password-sign-in' ||
+ (passwordSignIn && signInAttempt !== 'none') ||
+ (ownerSignIn && signInAttempt === 'owner-sign-in')
+ )
+ return refuse('invalid-input');
+ if (type !== 'team-sign-in' || signInAttempt === 'none') signInAttempt = type;
try {
- const result = ownerSignIn
- ? await options.memberDevices.signInOwner(input['input'], remoteAddress, publicKey)
- : await options.memberDevices.signIn(input['input'], remoteAddress, publicKey);
+ const devices = options.memberDevices;
+ if (!devices) throw new TeamError('password-sign-in-unavailable');
+ const signIn = passwordSignIn
+ ? devices.signInPassword
+ : ownerSignIn
+ ? devices.signInOwner
+ : devices.signIn;
+ const result = await signIn(input['input'], remoteAddress, publicKey);
const sent = send({ type: reply, result: { ok: true, value: result } });
- if (!sent && ownerSignIn) options.pairing.revoke(result.deviceId);
+ if (!sent) {
+ if (ownerSignIn || ('role' in result && result.role === 'owner'))
+ options.pairing.revoke(result.deviceId);
+ else if (passwordSignIn) await devices.revokeMemberSignIn(result.deviceId);
+ }
} catch (error) {
if (!closed)
send({
diff --git a/packages/core/src/devices/mount-gateway.ts b/packages/core/src/devices/mount-gateway.ts
index 569308e44d..80f91b99f9 100644
--- a/packages/core/src/devices/mount-gateway.ts
+++ b/packages/core/src/devices/mount-gateway.ts
@@ -15,6 +15,7 @@ import type { createConnectBotBridge } from './bot-connect-bridge.js';
import { BOT_CONNECT_PATH } from './bot-connect-channel.js';
import type { ConnectAccount } from './connect-account.js';
import type { createDevicesHttp } from './http.js';
+import { createChannelDiscovery } from './channel-discovery.js';
import type { createDevicePairing } from './pairing.js';
import type { ConnectionLike, WebServerLike } from './mount-types.js';
import {
@@ -111,6 +112,11 @@ export function mountDeviceGateway(
}
: undefined;
const { push, activity } = delivery();
+ const discover = createChannelDiscovery({
+ host: () => pairing.host(),
+ encryption,
+ passwordSignInAvailable: () => memberDevices?.passwordSignInAvailable() ?? false,
+ });
const gateway = createDeviceGateway({
...(team ? { team } : {}),
pairing,
@@ -139,29 +145,7 @@ export function mountDeviceGateway(
await connectBots.handle(request, response);
return;
}
- if (request.url === CONNECT_CHANNEL_PATH) {
- if (request.method !== 'GET') {
- response.writeHead(405);
- response.end();
- return;
- }
- try {
- const identity = await encryption();
- response.writeHead(200, {
- 'content-type': 'application/json',
- 'cache-control': 'no-store',
- 'access-control-allow-origin': '*',
- });
- response.end(JSON.stringify({ host: pairing.host(), encryption: identity }));
- } catch {
- response.writeHead(503, {
- 'content-type': 'application/json',
- 'cache-control': 'no-store',
- });
- response.end(JSON.stringify({ code: 'host-key-unavailable' }));
- }
- return;
- }
+ if (request.url === CONNECT_CHANNEL_PATH) return discover(request, response);
await gateway.handle(request, response);
},
}),
diff --git a/packages/core/src/team/devices.ts b/packages/core/src/team/devices.ts
index 261c6e88b4..d65f5fbecc 100644
--- a/packages/core/src/team/devices.ts
+++ b/packages/core/src/team/devices.ts
@@ -36,8 +36,15 @@ export function createMemberDevices(options: {
fingerprint: (await options.encryption()).fingerprint,
});
const routes = async () => memberUrls(await options.routes());
+ const issueOwner = (humanId: string, name: string, publicKey: string) => {
+ const issued = options.pairing.issueOwnerPasswordDevice({ humanId, name, publicKey });
+ if (!issued) throw new TeamError('credentials-invalid');
+ return issued;
+ };
return {
routes,
+ passwordSignInAvailable: () => options.team.passwordSignInAvailable(),
+ revokeMemberSignIn: (deviceId: string) => options.team.revoke(deviceId),
async invitation(humanId: string): Promise {
const member = options.team.member(humanId);
if (!member) throw new TeamError('member-not-found');
@@ -86,15 +93,23 @@ export function createMemberDevices(options: {
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 };
+ return options.team.signInOwnerDevice(parsed.username, parsed.password, ip, (humanId) => ({
+ ...issueOwner(humanId, parsed.deviceName, publicKey),
+ host: identity,
+ }));
+ },
+ async signInPassword(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');
+ const signed = await options.team.signInPasswordDevice({
+ username: parsed.username,
+ password: parsed.password,
+ ip,
+ device: { kind: 'paired-device', name: parsed.deviceName, publicKey },
+ issueOwner: (humanId) => issueOwner(humanId, parsed.deviceName, publicKey),
});
+ return { ...signed.device, role: signed.role, host: identity };
},
};
}
diff --git a/packages/core/src/team/member-auth.ts b/packages/core/src/team/member-auth.ts
index e5e4a2f0ae..f716b04a86 100644
--- a/packages/core/src/team/member-auth.ts
+++ b/packages/core/src/team/member-auth.ts
@@ -113,12 +113,21 @@ export async function signIn(
const credential = member ? this.credential(member.humanId) : undefined;
const valid = await verifyPassword(password, credential?.hash ?? DUMMY_PASSWORD_HASH);
if (!valid || !member) throw new TeamError('credentials-invalid');
- if (this.credential(member.humanId)?.hash.hash !== credential?.hash.hash)
+ return signInMemberGrant.call(this, member, credential?.hash.hash, device);
+}
+
+async function signInMemberGrant(
+ this: MemberAuthHost,
+ member: TeamMember,
+ verifiedHash: string | undefined,
+ device?: { kind: 'paired-device'; name: string; publicKey?: string },
+): Promise<{ token: string; member: TeamMember; peer: PeerScope }> {
+ if (this.credential(member.humanId)?.hash.hash !== verifiedHash)
throw new TeamError('credentials-invalid');
this.active(this.member(member.humanId));
this.spaceProvider?.().ensureAccount(member.humanId);
if (member.owner) await this.ensureTob?.(humanContext(member.humanId));
- if (this.credential(member.humanId)?.hash.hash !== credential?.hash.hash)
+ if (this.credential(member.humanId)?.hash.hash !== verifiedHash)
throw new TeamError('credentials-invalid');
this.active(this.member(member.humanId));
return { ...this.createGrant(member, device), member };
@@ -132,6 +141,49 @@ function ownerPasswordEnabled(db: MemberAuthHost['db']): boolean {
);
}
+export function passwordSignInAvailable(this: MemberAuthHost): boolean {
+ return this.db.read(
+ (db) =>
+ db
+ .prepare(`SELECT owner_password_sign_in OR (enabled AND EXISTS (
+ SELECT 1 FROM member_credentials c JOIN humans h USING(human_id)
+ WHERE c.human_id <> team_settings.owner_human_id AND h.status = 'active'
+ )) AS available FROM team_settings WHERE singleton = 1`)
+ .get()?.available === 1,
+ );
+}
+
+export async function signInPasswordDevice(
+ this: MemberAuthHost,
+ input: {
+ username: string;
+ password: string;
+ ip: string;
+ device: { kind: 'paired-device'; name: string; publicKey: string };
+ issueOwner: (humanId: string) => T;
+ },
+): Promise<
+ | { role: 'owner'; device: T }
+ | { role: 'member'; device: ReturnType }
+> {
+ if (!passwordSignInAvailable.call(this)) throw new TeamError('password-sign-in-unavailable');
+ this.passwordAttempt(input.username, input.ip);
+ const member = this.byUsername(input.username);
+ const credential = member && this.credential(member.humanId);
+ const valid = await verifyPassword(input.password, credential?.hash ?? DUMMY_PASSWORD_HASH);
+ if (!valid || !member || !credential) throw new TeamError('credentials-invalid');
+
+ if (member.owner) {
+ const humanId = ownerPasswordIdentity.call(this, member.humanId, credential.hash.hash);
+ return { role: 'owner', device: input.issueOwner(humanId) };
+ }
+ const current = this.member(member.humanId);
+ if (current?.owner) throw new TeamError('credentials-invalid');
+ this.active(current);
+ const grant = await signInMemberGrant.call(this, current, credential.hash.hash, input.device);
+ return { role: 'member', device: this.deviceGrantResult(grant, grant.member) };
+}
+
export async function setOwnerPassword(
this: MemberAuthHost,
human: HumanContext,
@@ -238,13 +290,21 @@ export async function signInOwnerDevice(
const matches = credential?.username === username;
const valid = await verifyPassword(password, matches ? credential.hash : DUMMY_PASSWORD_HASH);
if (!matches || !valid) throw new TeamError('credentials-invalid');
+ return issue(ownerPasswordIdentity.call(this, humanId, credential.hash.hash));
+}
+
+function ownerPasswordIdentity(
+ this: MemberAuthHost,
+ humanId: string,
+ verifiedHash: string,
+): string {
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
+ this.credential(humanId)?.hash.hash !== verifiedHash
)
throw new TeamError('credentials-invalid');
- return issue(humanId);
+ return humanId;
}
export function createGrant(
diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts
index e721d58a7e..16c60aa276 100644
--- a/packages/core/src/team/service.ts
+++ b/packages/core/src/team/service.ts
@@ -709,6 +709,14 @@ export class TeamService {
);
}
+ passwordSignInAvailable(): boolean {
+ return memberAuth.passwordSignInAvailable.call(this.#memberOperations);
+ }
+
+ signInPasswordDevice(input: Parameters>[0]) {
+ return (memberAuth.signInPasswordDevice).call(this.#memberOperations, input);
+ }
+
private createGrant(
member: TeamMember,
device?: { kind: 'paired-device'; name: string; publicKey?: string },
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 9f6116fe93..c9040ca480 100644
--- a/packages/core/test/owner-password-device-sign-in.test.ts
+++ b/packages/core/test/owner-password-device-sign-in.test.ts
@@ -1,11 +1,15 @@
import { randomBytes } from 'node:crypto';
+import type { AddressInfo } from 'node:net';
import { encryptedCarrier, openNoiseSocket } from '@botharness/host-client/encrypted-carrier';
+import { signInWithPassword } from '@botharness/host-client/password-sign-in';
import { Peer } from '@deepseek-ai/dsh-client-connection';
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';
+import { createGatewayOrigin } from '../src/devices/connect.js';
+import * as passwordHashing from '../src/team/password.js';
+import { cleanup, enabledFixture, memberDeviceHost, teamFixture } from './team-mode-fixtures.js';
afterEach(cleanup);
@@ -26,6 +30,15 @@ async function signIn(
attempt = password,
fingerprint = f.encryption.fingerprint,
repeat = false,
+ type = 'owner-sign-in',
+ repeatType = type,
+ }: {
+ username?: string;
+ attempt?: string;
+ fingerprint?: string;
+ repeat?: boolean;
+ type?: 'owner-sign-in' | 'password-sign-in';
+ repeatType?: 'owner-sign-in' | 'password-sign-in';
} = {},
) {
return new Promise((resolve, reject) => {
@@ -41,7 +54,8 @@ async function signIn(
socket.close();
return;
}
- if (frame['type'] !== 'owner-signed-in') return;
+ const reply = type === 'password-sign-in' ? 'password-signed-in' : 'owner-signed-in';
+ if (frame['type'] !== reply) return;
result = frame['result'];
if (!repeat) {
resolve(result);
@@ -52,15 +66,148 @@ async function signIn(
});
void socket.ready.then(() => {
const request = {
- type: 'owner-sign-in',
+ type,
input: { username, password: attempt, deviceName: 'Desktop', fingerprint },
};
socket.send(request);
- if (repeat) socket.send(request);
+ if (repeat) socket.send({ ...request, type: repeatType });
}, reject);
});
}
+it('discovers password availability at the Host and through the Connect origin', async () => {
+ const f = await enabledFixture();
+ const host = await memberDeviceHost(f);
+ const proxy = createGatewayOrigin(() => Number(new URL(host.origin).port));
+ await new Promise((resolve) => proxy.listen(0, '127.0.0.1', resolve));
+ const proxyOrigin = `http://127.0.0.1:${(proxy.address() as AddressInfo).port}`;
+ const discover = async (password: boolean) => {
+ for (const origin of [host.origin, proxyOrigin]) {
+ const response = await fetch(origin + '/botharness-device/channel');
+ expect(response.status).toBe(200);
+ expect(response.headers.get('cache-control')).toBe('no-store');
+ expect(await response.json()).toEqual({
+ host: f.pairing.host(),
+ encryption: f.encryption,
+ signIn: { password },
+ });
+ }
+ };
+ try {
+ await discover(true);
+ await f.team.suspend(owner, f.human.humanId);
+ await discover(false);
+ await f.team.setMode(owner, false);
+ await f.team.ownerPasswordSignInSet(owner, { enabled: true });
+ await discover(true);
+ await f.team.ownerPasswordSignInSet(owner, { enabled: false });
+ await discover(false);
+ } finally {
+ proxy.closeAllConnections();
+ await new Promise((resolve) => proxy.close(() => resolve()));
+ }
+});
+
+it('uses the existing Owner and member grants for unified password sign-in', async () => {
+ const f = await enabledFixture();
+ await f.team.ownerPasswordSignInSet(owner, { enabled: true });
+ const host = await memberDeviceHost(f);
+ const enroll = (username: string, password: string) =>
+ signInWithPassword({
+ carrier: host.carrier,
+ route: target,
+ username,
+ password,
+ deviceName: 'Phone',
+ });
+ const signedOwner = await enroll('owner', 'owner-password-1');
+ expect(signedOwner).toMatchObject({ ok: true, value: { role: 'owner' } });
+ expect(f.pairing.list()).toMatchObject([{ enrollment: 'owner-password' }]);
+ const member = await enroll('bob', f.initialPassword);
+ expect(member).toMatchObject({
+ ok: true,
+ value: { role: 'member', member: { humanId: f.human.humanId, mustChangePassword: true } },
+ });
+ if (!member.ok || !member.value.encryption) throw new Error('missing member grant');
+ const { credential, encryption } = member.value;
+ expect(f.team.admitDevice(`Device ${credential}`, f.encryption.publicKey)).toBeUndefined();
+ expect(f.pairing.list()).toHaveLength(1);
+ expect(credential).toMatch(/^member\./u);
+ const deviceKey = Buffer.from(encryption.deviceKey, 'hex');
+ const { noisePublicKey } = await import('@botharness/host-protocol/noise/xk');
+ expect(
+ f.team.admitDevice(
+ `Device ${credential}`,
+ Buffer.from(noisePublicKey(deviceKey)).toString('hex'),
+ )?.principal,
+ ).toMatchObject({ kind: 'botharness-member', humanId: f.human.humanId });
+});
+
+it('uses identical refusals and hash costs for wrong and unknown passwords, including a disabled Owner', async () => {
+ const f = await enabledFixture();
+ const host = await memberDeviceHost(f);
+ const authenticate = (username: string, attempt: string) =>
+ signIn(f, host, deviceEncryption(f), { type: 'password-sign-in', username, attempt });
+ const verify = vi.spyOn(passwordHashing, 'verifyPassword');
+ try {
+ for (const username of ['owner', 'bob', 'no-such-user'])
+ expect(await authenticate(username, 'wrong')).toEqual({
+ ok: false,
+ code: 'credentials-invalid',
+ });
+ expect(verify.mock.calls.map(([, hash]) => hash.params)).toEqual(
+ Array.from({ length: 3 }, () => passwordHashing.ARGON2_PARAMS),
+ );
+ expect(verify).toHaveBeenLastCalledWith('wrong', passwordHashing.DUMMY_PASSWORD_HASH);
+ expect(await authenticate('owner', 'owner-password-1')).toEqual({
+ ok: false,
+ code: 'owner-sign-in-disabled',
+ });
+ await f.team.setMode(owner, false);
+ expect(await authenticate('owner', 'owner-password-1')).toEqual({
+ ok: false,
+ code: 'password-sign-in-unavailable',
+ });
+ } finally {
+ verify.mockRestore();
+ }
+});
+
+it.each([
+ ['password-sign-in', 'password-sign-in'],
+ ['password-sign-in', 'owner-sign-in'],
+ ['owner-sign-in', 'password-sign-in'],
+] as const)(
+ 'allows only one password attempt when %s is followed by %s',
+ async (type, repeatType) => {
+ const f = teamFixture();
+ await f.team.ownerPasswordSignInSet(owner, { enabled: true, username: 'my-owner', password });
+ const host = await memberDeviceHost(f);
+ await expect(
+ signIn(f, host, deviceEncryption(f), { type, repeatType, repeat: true }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(f.pairing.list()).toHaveLength(1);
+ },
+);
+
+it('shares one username limit between unified and standalone Owner sign-in', async () => {
+ const f = teamFixture();
+ await f.team.ownerPasswordSignInSet(owner, { enabled: true, username: 'my-owner', password });
+ const host = await memberDeviceHost(f);
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const type = attempt % 2 === 0 ? 'password-sign-in' : 'owner-sign-in';
+ expect(await signIn(f, host, deviceEncryption(f), { type, attempt: 'wrong' })).toEqual({
+ ok: false,
+ code: 'credentials-invalid',
+ });
+ }
+ expect(await signIn(f, host, deviceEncryption(f), { type: 'password-sign-in' })).toEqual({
+ ok: false,
+ code: 'rate-limited',
+ retryAfterSeconds: 60,
+ });
+});
+
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);
diff --git a/packages/core/test/team-mode-fixtures.ts b/packages/core/test/team-mode-fixtures.ts
index 9a5dd0f6f8..17ed4fefce 100644
--- a/packages/core/test/team-mode-fixtures.ts
+++ b/packages/core/test/team-mode-fixtures.ts
@@ -2,6 +2,7 @@ import { createDevicePairing } from '../src/devices/pairing.js';
import { createMemberDevices } from '../src/team/devices.js';
import { createDeviceGateway } from '../src/devices/gateway.js';
import { createEncryptedGateway } from '../src/devices/encrypted-gateway.js';
+import { createChannelDiscovery } from '../src/devices/channel-discovery.js';
import {
noisePublicKey,
noiseFingerprint,
@@ -351,10 +352,14 @@ export async function memberDeviceHost(
key: async () => Uint8Array.from(f.privateKey),
port: () => port,
});
+ const discover = createChannelDiscovery({
+ host: () => f.pairing.host(),
+ encryption: async () => f.encryption,
+ passwordSignInAvailable: f.devices.passwordSignInAvailable,
+ });
const server = createServer((req, res) => {
if (req.url === '/botharness-device/channel') {
- res.setHeader('content-type', 'application/json');
- res.end(JSON.stringify({ host: f.pairing.host(), encryption: f.encryption }));
+ void discover(req, res);
return;
}
if (options.remote)
diff --git a/packages/host-client/src/encrypted-sign-in.ts b/packages/host-client/src/encrypted-sign-in.ts
index 38ea8651d5..033bf981e4 100644
--- a/packages/host-client/src/encrypted-sign-in.ts
+++ b/packages/host-client/src/encrypted-sign-in.ts
@@ -36,7 +36,7 @@ export function signInRefusal(
}
export function encryptedSignIn(options: {
- type: 'owner-sign-in' | 'team-sign-in';
+ type: 'owner-sign-in' | 'team-sign-in' | 'password-sign-in';
carrier: HostCarrier;
route: string;
host: TeamHostIdentity;
@@ -63,7 +63,11 @@ export function encryptedSignIn(options: {
abort();
return;
}
- const replyType = options.type === 'owner-sign-in' ? 'owner-signed-in' : 'team-signed-in';
+ const replyType = {
+ 'owner-sign-in': 'owner-signed-in',
+ 'team-sign-in': 'team-signed-in',
+ 'password-sign-in': 'password-signed-in',
+ }[options.type];
try {
socket = openNoiseSocket({
origin: options.route,
@@ -73,6 +77,10 @@ export function encryptedSignIn(options: {
closed: (reason) =>
finish(signInTransportFailure(new ConnectRefused(reason), options.signal)),
message: (frame) => {
+ if (options.type === 'password-sign-in' && frame['type'] === 'refused') {
+ finish(signInRefusal(frame, options.codes));
+ return;
+ }
if (frame['type'] !== replyType) return;
const result = teamRecord(frame['result']);
finish(
diff --git a/packages/host-client/src/owner-sign-in.ts b/packages/host-client/src/owner-sign-in.ts
index 3607d8335c..7142a0f52a 100644
--- a/packages/host-client/src/owner-sign-in.ts
+++ b/packages/host-client/src/owner-sign-in.ts
@@ -3,6 +3,7 @@ import { isHttpsOrigin } from '@botharness/host-protocol/route';
import {
teamHostIdentity,
teamRecord,
+ type TeamHostIdentity,
type TeamResult,
} from '@botharness/host-protocol/team-invitation';
import { keyHex, secureRandom } from './encrypted-carrier';
@@ -10,7 +11,7 @@ import { encryptedSignIn, signInTransportFailure } from './encrypted-sign-in';
import type { HostEncryption, SavedHost } from './hosts';
import { discoverSignInHost, matchesSavedSignInHost } from './sign-in-discovery';
-const refusals = [
+export const ownerSignInRefusals = [
'credentials-invalid',
'rate-limited',
'owner-sign-in-disabled',
@@ -21,7 +22,7 @@ const refusals = [
] as const;
export type OwnerSignInError =
- | (typeof refusals)[number]
+ | (typeof ownerSignInRefusals)[number]
| 'already-paired'
| 'this-host'
| 'response-invalid'
@@ -40,9 +41,51 @@ export interface OwnerSignInOptions {
signal?: AbortSignal;
}
+export function ownerSignInOrigin(input: string): string | undefined {
+ const value = input.trim();
+ if (!/^(?:https:\/\/)?[^/\\?#@\s]+\/?$/iu.test(value)) return undefined;
+ try {
+ const url = new URL(value.includes('://') ? value : 'https://' + value);
+ if (
+ isHttpsOrigin(url.origin) &&
+ !url.username &&
+ !url.password &&
+ !url.hash &&
+ !url.search &&
+ url.pathname === '/'
+ )
+ return url.origin;
+ } catch {}
+}
+
export async function signInOwnerDevice(
options: OwnerSignInOptions,
): Promise> {
+ return withPasswordSignInChannel(options, async ({ host, encryption, signal }) => {
+ const { carrier, route, username, password, deviceName } = options;
+ const result = await encryptedSignIn({
+ type: 'owner-sign-in',
+ carrier,
+ route,
+ host,
+ encryption,
+ signal,
+ input: { username, password, deviceName, fingerprint: host.fingerprint },
+ codes: ownerSignInRefusals,
+ });
+ return result.ok ? signedOwnerHost(result.value, host, route, encryption) : result;
+ });
+}
+
+export async function withPasswordSignInChannel(
+ options: OwnerSignInOptions,
+ run: (channel: {
+ host: TeamHostIdentity;
+ encryption: HostEncryption;
+ signal: AbortSignal;
+ signIn?: { password: boolean };
+ }) => Promise>,
+): Promise> {
const { carrier, route, username, password, deviceName } = options;
if (!isHttpsOrigin(route)) return { ok: false, code: 'insecure-transport' };
if (
@@ -66,8 +109,9 @@ export async function signInOwnerDevice(
redirect: 'error',
signal,
});
+ if (signal.aborted) return { ok: false, code: 'request-cancelled' };
if (!discovered.ok) return discovered;
- const { host, publicKey } = discovered.value;
+ const { host, publicKey, signIn } = discovered.value;
if (host.id === options.localHostId) return { ok: false, code: 'this-host' };
const previous = options.previous?.(host.id, route);
if (!matchesSavedSignInHost(previous, host, publicKey))
@@ -80,40 +124,38 @@ export async function signInOwnerDevice(
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,
- },
- };
+ return await run({ host, encryption, signal, ...(signIn === undefined ? {} : { signIn }) });
} catch (error) {
return signInTransportFailure(error, signal);
}
}
+
+export function signedOwnerHost(
+ value: unknown,
+ host: TeamHostIdentity,
+ route: string,
+ encryption: HostEncryption,
+): TeamResult {
+ const { host: reply, deviceId, credential } = teamRecord(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,
+ },
+ };
+}
diff --git a/packages/host-client/src/password-sign-in.ts b/packages/host-client/src/password-sign-in.ts
new file mode 100644
index 0000000000..c28bc9fac3
--- /dev/null
+++ b/packages/host-client/src/password-sign-in.ts
@@ -0,0 +1,106 @@
+import type { HostCarrier } from '@botharness/host-protocol/carrier';
+import {
+ teamRecord,
+ type TeamHostIdentity,
+ type TeamResult,
+} from '@botharness/host-protocol/team-invitation';
+import { encryptedSignIn, signInTransportFailure } from './encrypted-sign-in';
+import type { SavedHost } from './hosts';
+import {
+ ownerSignInOrigin,
+ ownerSignInRefusals,
+ signedOwnerHost,
+ withPasswordSignInChannel,
+ type OwnerSignInError,
+ type OwnerSignInOptions,
+} from './owner-sign-in';
+import { discoverSignInHost } from './sign-in-discovery';
+import { signedMemberHost } from './team-client';
+
+export type PasswordSignInError =
+ | OwnerSignInError
+ | 'password-sign-in-unavailable'
+ | 'host-update-required'
+ | 'team-mode-off'
+ | 'member-suspended';
+
+export interface HostAddressDiscovery {
+ route: string;
+ host: TeamHostIdentity;
+ publicKey: string;
+ signIn?: { password: boolean };
+}
+
+export async function discoverHostAddress(options: {
+ carrier: HostCarrier;
+ input: string;
+ signal?: AbortSignal;
+}): Promise<
+ TeamResult<
+ HostAddressDiscovery,
+ | 'insecure-transport'
+ | 'unreachable'
+ | 'response-invalid'
+ | 'fingerprint-mismatch'
+ | 'request-cancelled'
+ >
+> {
+ const route = ownerSignInOrigin(options.input);
+ if (!route) return { ok: false, code: 'insecure-transport' };
+ const signal = AbortSignal.any([
+ AbortSignal.timeout(30_000),
+ ...(options.signal ? [options.signal] : []),
+ ]);
+ if (signal.aborted) return { ok: false, code: 'request-cancelled' };
+ try {
+ const result = await discoverSignInHost({
+ carrier: options.carrier,
+ route,
+ signal,
+ redirect: 'error',
+ });
+ if (signal.aborted) return { ok: false, code: 'request-cancelled' };
+ return result.ok ? { ok: true, value: { route, ...result.value } } : result;
+ } catch (error) {
+ return signInTransportFailure(error, signal);
+ }
+}
+
+const refusals = [
+ ...ownerSignInRefusals,
+ 'password-sign-in-unavailable',
+ 'host-update-required',
+ 'team-mode-off',
+ 'member-suspended',
+] as const;
+
+export async function signInWithPassword(
+ options: OwnerSignInOptions,
+): Promise> {
+ return withPasswordSignInChannel(
+ options,
+ async ({ host, encryption, signal, signIn }) => {
+ if (signIn === undefined) return { ok: false, code: 'host-update-required' };
+ if (!signIn.password) return { ok: false, code: 'password-sign-in-unavailable' };
+ const { carrier, route, username, password, deviceName } = options;
+ const result = await encryptedSignIn({
+ type: 'password-sign-in',
+ carrier,
+ route,
+ host,
+ encryption,
+ signal,
+ input: { username, password, deviceName, fingerprint: host.fingerprint },
+ codes: refusals,
+ });
+ if (!result.ok) return result;
+ const role = teamRecord(result.value)['role'];
+ if (role !== 'owner' && role !== 'member') return { ok: false, code: 'response-invalid' };
+ const saved =
+ role === 'owner'
+ ? signedOwnerHost(result.value, host, route, encryption)
+ : signedMemberHost(result.value, { host, username, routes: [route] }, route, encryption);
+ return saved.ok ? { ok: true, value: { ...saved.value, role } } : saved;
+ },
+ );
+}
diff --git a/packages/host-client/src/sign-in-discovery.ts b/packages/host-client/src/sign-in-discovery.ts
index 10c77ca8ab..c277ca4710 100644
--- a/packages/host-client/src/sign-in-discovery.ts
+++ b/packages/host-client/src/sign-in-discovery.ts
@@ -18,7 +18,7 @@ export async function discoverSignInHost(options: {
invitedHost?: TeamHostIdentity;
}): Promise<
TeamResult<
- { host: TeamHostIdentity; publicKey: string },
+ { host: TeamHostIdentity; publicKey: string; signIn?: { password: boolean } },
'unreachable' | 'response-invalid' | 'fingerprint-mismatch'
>
> {
@@ -30,7 +30,13 @@ export async function discoverSignInHost(options: {
});
if (response.status !== 200) return { ok: false, code: 'unreachable' };
- const discovery = teamRecord(JSON.parse(await response.text()));
+ const body = await response.text();
+ let discovery: Record;
+ try {
+ discovery = teamRecord(JSON.parse(body));
+ } catch {
+ return { ok: false, code: 'response-invalid' };
+ }
const identity = teamRecord(discovery['host']);
const encryption = teamRecord(discovery['encryption']);
const publicKey = encryption['publicKey'];
@@ -46,7 +52,11 @@ export async function discoverSignInHost(options: {
(invitedHost && (invitedHost.id !== host.id || invitedHost.fingerprint !== host.fingerprint))
)
return { ok: false, code: 'fingerprint-mismatch' };
- return { ok: true, value: { host, publicKey } };
+ const password = teamRecord(discovery['signIn'])['password'];
+ return {
+ ok: true,
+ value: { host, publicKey, ...(typeof password === 'boolean' ? { signIn: { password } } : {}) },
+ };
}
export function matchesSavedSignInHost(
diff --git a/packages/host-client/src/team-client.ts b/packages/host-client/src/team-client.ts
index f4bd188b0a..f96391e349 100644
--- a/packages/host-client/src/team-client.ts
+++ b/packages/host-client/src/team-client.ts
@@ -36,12 +36,12 @@ const codes: readonly TeamErrorCode[] = [
'invalid-input',
'remote-access/denied',
];
-function signedHost(
+export function signedMemberHost(
input: unknown,
- invitation: TeamInvitation,
+ invitation: Pick,
route: string,
encryption: HostEncryption,
-): TeamResult {
+): TeamResult {
const value = teamRecord(input);
const host = teamHostIdentity(value['host']);
if (!host || host.id !== invitation.host.id || host.fingerprint !== invitation.host.fingerprint)
@@ -162,7 +162,7 @@ async function signInTeamRoute(
input,
signal,
});
- return result.ok ? signedHost(result.value, invitation, route, encryption) : result;
+ return result.ok ? signedMemberHost(result.value, invitation, route, encryption) : result;
}
const result = await options.carrier.request(`${route}/botharness-device/team/device-sign-in`, {
method: 'POST',
@@ -172,7 +172,7 @@ async function signInTeamRoute(
});
const value: unknown = JSON.parse(await result.text());
return result.status === 200
- ? signedHost(value, invitation, route, encryption)
+ ? signedMemberHost(value, invitation, route, encryption)
: signInRefusal(value, codes);
} catch (error) {
return signInTransportFailure(error, signal);
diff --git a/packages/host-client/test/owner-sign-in.test.ts b/packages/host-client/test/owner-sign-in.test.ts
index 6690d2f625..0df550c7f8 100644
--- a/packages/host-client/test/owner-sign-in.test.ts
+++ b/packages/host-client/test/owner-sign-in.test.ts
@@ -6,8 +6,9 @@ import { noiseFingerprint, noisePublicKey } from '@botharness/host-protocol/nois
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 { parseSavedHost, serializeSavedHost, type SavedHost } from '../src/hosts';
import { signInOwnerDevice } from '../src/owner-sign-in';
+import { discoverHostAddress, signInWithPassword } from '@botharness/host-client/password-sign-in';
const route = 'https://studio.example';
const password = 'test-only-sign-in-password';
@@ -15,7 +16,15 @@ const deviceId = 'test-device-1234';
const credential = deviceId + '.' + 'a'.repeat(43);
const avatarPath = '/api/bots/avatar';
-function host({ differentSocketKey = false } = {}) {
+function host({
+ differentSocketKey = false,
+ passwordAvailable,
+ passwordReply,
+}: {
+ differentSocketKey?: boolean;
+ passwordAvailable?: boolean;
+ passwordReply?: object;
+} = {}) {
const privateKey = randomBytes(32);
const publicKey = noisePublicKey(privateKey);
const identity = { id: 'studio', name: 'Studio', fingerprint: noiseFingerprint(publicKey) };
@@ -25,7 +34,12 @@ function host({ differentSocketKey = false } = {}) {
};
const request = vi.fn(async (_url: string, _init: HostRequest) => ({
status: 200,
- text: async () => JSON.stringify({ host: identity, encryption }),
+ text: async () =>
+ JSON.stringify({
+ host: identity,
+ encryption,
+ ...(passwordAvailable === undefined ? {} : { signIn: { password: passwordAvailable } }),
+ }),
}));
const messages: unknown[] = [];
const wire: string[] = [];
@@ -54,6 +68,14 @@ function host({ differentSocketKey = false } = {}) {
type: 'owner-signed-in',
result: { ok: true, value: { host: identity, deviceId, credential } },
});
+ if (message['type'] === 'password-sign-in')
+ send({
+ type: 'password-signed-in',
+ result: passwordReply ?? {
+ ok: true,
+ value: { host: identity, deviceId, credential, role: 'owner' },
+ },
+ });
if (message['type'] === 'admit' && message['credential'] === credential)
send({ type: 'admitted' });
if (message['type'] === 'request') {
@@ -86,6 +108,7 @@ function host({ differentSocketKey = false } = {}) {
messages,
wire,
encryption,
+ identity,
input: { carrier, route, username: 'owner', password, deviceName: 'Desktop' },
};
}
@@ -240,3 +263,135 @@ describe('Owner password sign-in', () => {
expect(test.openSocket).not.toHaveBeenCalled();
});
});
+
+describe('HTTPS address discovery and unified sign-in', () => {
+ it.each([true, false, undefined])(
+ 'normalizes a typed address and returns password availability %s',
+ async (passwordAvailable) => {
+ const test = host(passwordAvailable === undefined ? {} : { passwordAvailable });
+ expect(
+ await discoverHostAddress({ carrier: test.carrier, input: ' Studio.Example/ ' }),
+ ).toEqual({
+ ok: true,
+ value: {
+ route,
+ host: test.identity,
+ publicKey: test.encryption.publicKey,
+ ...(passwordAvailable === undefined ? {} : { signIn: { password: passwordAvailable } }),
+ },
+ });
+ expect(test.request).toHaveBeenCalledWith(route + '/botharness-device/channel', {
+ method: 'GET',
+ redirect: 'error',
+ signal: expect.any(AbortSignal),
+ });
+ expect(test.openSocket).not.toHaveBeenCalled();
+ },
+ );
+
+ it('codes cancellation, unreachable responses, malformed JSON and fingerprint mismatches', async () => {
+ const test = host();
+ const discover = (signal?: AbortSignal) =>
+ discoverHostAddress({ carrier: test.carrier, input: route, ...(signal ? { signal } : {}) });
+ expect(await discover(AbortSignal.abort())).toEqual({ ok: false, code: 'request-cancelled' });
+ expect(test.request).not.toHaveBeenCalled();
+ test.request.mockRejectedValueOnce(new Error('discovery redirect'));
+ expect(await discover()).toEqual({ ok: false, code: 'unreachable' });
+ test.request.mockResolvedValueOnce({ status: 200, text: async () => '{' });
+ expect(await discover()).toEqual({ ok: false, code: 'response-invalid' });
+ test.request.mockResolvedValueOnce({
+ status: 200,
+ text: async () =>
+ JSON.stringify({
+ host: test.identity,
+ encryption: { ...test.encryption, fingerprint: '01'.repeat(32) },
+ }),
+ });
+ expect(await discover()).toEqual({ ok: false, code: 'fingerprint-mismatch' });
+ expect(test.openSocket).not.toHaveBeenCalled();
+ });
+
+ it('uses the unified frame and saves the Owner grant', async () => {
+ const test = host({ passwordAvailable: true });
+ expect(await signInWithPassword(test.input)).toMatchObject({
+ ok: true,
+ value: { role: 'owner', hostId: 'studio', routes: [route], credential, deviceId },
+ });
+ expect(test.messages).toEqual([
+ expect.objectContaining({
+ type: 'password-sign-in',
+ input: {
+ username: 'owner',
+ password,
+ deviceName: 'Desktop',
+ fingerprint: test.identity.fingerprint,
+ },
+ }),
+ ]);
+ expect(test.wire.join('')).not.toContain(password);
+ });
+
+ it.each([
+ [undefined, 'host-update-required'],
+ [false, 'password-sign-in-unavailable'],
+ ] as const)('does not send a password when discovery advertises %s', async (available, code) => {
+ const test = host(available === undefined ? {} : { passwordAvailable: available });
+ expect(await signInWithPassword(test.input)).toEqual({ ok: false, code });
+ expect(test.openSocket).not.toHaveBeenCalled();
+ });
+
+ it('checks the existing pairing, local Host and encryption before submitting a password', async () => {
+ const test = host({ passwordAvailable: true, differentSocketKey: true });
+ const previous: SavedHost = {
+ hostId: 'studio',
+ hostName: 'Studio',
+ deviceId,
+ credential,
+ routes: [route],
+ encryption: {
+ protocol: 'connect-noise-xk-v1',
+ hostKey: test.encryption.publicKey,
+ deviceKey: 'ab'.repeat(32),
+ },
+ };
+ expect(await signInWithPassword({ ...test.input, localHostId: 'studio' })).toEqual({
+ ok: false,
+ code: 'this-host',
+ });
+ expect(
+ await signInWithPassword({
+ ...test.input,
+ previous: () => previous,
+ allowExisting: () => false,
+ }),
+ ).toEqual({ ok: false, code: 'already-paired' });
+ expect(
+ await signInWithPassword({
+ ...test.input,
+ previous: () => ({
+ ...previous,
+ encryption: { ...previous.encryption!, hostKey: 'ef'.repeat(32) },
+ }),
+ }),
+ ).toEqual({ ok: false, code: 'fingerprint-mismatch' });
+ expect(test.openSocket).not.toHaveBeenCalled();
+ expect(
+ await signInWithPassword({
+ ...test.input,
+ previous: () => previous,
+ allowExisting: () => true,
+ }),
+ ).toEqual({ ok: false, code: 'fingerprint-mismatch' });
+ expect(test.openSocket).toHaveBeenCalledOnce();
+ expect(test.messages).toHaveLength(0);
+ });
+
+ it.each(['rate-limited', 'team-mode-off', 'member-suspended'] as const)(
+ 'preserves the %s refusal for the phone to explain',
+ async (code) => {
+ const refusal = { ok: false, code, retryAfterSeconds: 10 };
+ const test = host({ passwordAvailable: true, passwordReply: refusal });
+ expect(await signInWithPassword(test.input)).toEqual(refusal);
+ },
+ );
+});
diff --git a/packages/host-client/test/password-sign-in-origin.property.test.ts b/packages/host-client/test/password-sign-in-origin.property.test.ts
new file mode 100644
index 0000000000..7cabe67035
--- /dev/null
+++ b/packages/host-client/test/password-sign-in-origin.property.test.ts
@@ -0,0 +1,29 @@
+import fc from 'fast-check';
+import { expect, it, vi } from 'vitest';
+import type { HostCarrier } from '@botharness/host-protocol/carrier';
+import { discoverHostAddress } from '@botharness/host-client/password-sign-in';
+
+it('rejects paths, user information, query strings and fragments before requesting discovery', async () => {
+ const carrier: HostCarrier = {
+ request: vi.fn(),
+ openSocket: vi.fn(),
+ };
+ await fc.assert(
+ fc.asyncProperty(fc.integer({ min: 1 }), async (segment) => {
+ const host = 'studio.example';
+ for (const input of [
+ `https://${host}/${segment}/..`,
+ `https://${host}?${segment}`,
+ `https://${host}#${segment}`,
+ `https://${segment}@${host}`,
+ `http://${host}:${(segment % 65535) + 1}`,
+ ]) {
+ expect(await discoverHostAddress({ carrier, input })).toEqual({
+ ok: false,
+ code: 'insecure-transport',
+ });
+ }
+ }),
+ );
+ expect(carrier.request).not.toHaveBeenCalled();
+});