diff --git a/apps/mobile/app/+native-intent.tsx b/apps/mobile/app/+native-intent.tsx
index f0d4c837ff..d1c799434e 100644
--- a/apps/mobile/app/+native-intent.tsx
+++ b/apps/mobile/app/+native-intent.tsx
@@ -9,6 +9,8 @@ import { isSharePath } from '../src/ui/share/share-path';
export async function redirectSystemPath({ path }: { path: string; initial: boolean }) {
if (isConnectOAuthCallback(path)) return null;
if (isSharePath(path)) return '/share';
+ const team = /^(?:deepseekbot:\/\/|\/)team\?(?:.*&)?i=([A-Za-z0-9_-]+)/u.exec(path);
+ if (team !== null) return `/pair/team?i=${team[1]}`;
const call = callLinkRedirect(
path,
__DEV__ && Application.applicationId?.endsWith('.dev') === true,
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index f262b8815d..832f28c2af 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -314,6 +314,10 @@ function RootNavigator() {
name="sign-in"
options={{ ...sheetScreenOptions(design, true), title: t.emailSignIn.title }}
/>
+
+ {host?.member ? (
+
+
+
+ router.push({ pathname: '/member-pairing', params: { hostId: host.hostId } })
+ }
+ />
+
+ ) : null}
{host && client ? (
{busy === 'preference' ? (
diff --git a/apps/mobile/app/member-pairing.tsx b/apps/mobile/app/member-pairing.tsx
new file mode 100644
index 0000000000..584b9ea1e0
--- /dev/null
+++ b/apps/mobile/app/member-pairing.tsx
@@ -0,0 +1,103 @@
+import { useLocalSearchParams, useRouter } from 'expo-router';
+import { useState } from 'react';
+import { View } from 'react-native';
+import Svg, { Path } from 'react-native-svg';
+
+import { useHostSession } from '../src/host/host-session';
+import { memberPairingOffer, type MemberPairingOffer } from '../src/host/team-client';
+import { qrCode, radius, space } from '../src/ui/design/tokens';
+import { useMounted } from '../src/ui/mounted';
+import { Button } from '../src/ui/primitives/button';
+import { SheetHeader } from '../src/ui/primitives/sheet-header';
+import { SettingsForm, SettingsFormItem } from '../src/ui/primitives/settings-form';
+import { SheetScreen } from '../src/ui/primitives/sheet-screen';
+import { Text } from '../src/ui/primitives/text';
+import { useStrings } from '../src/ui/strings';
+
+const QR_SIZE = 220;
+
+export default function MemberPairingScreen() {
+ const t = useStrings();
+ const copy = t.memberPairing;
+ const router = useRouter();
+ const { hostId } = useLocalSearchParams<{ hostId?: string }>();
+ const session = useHostSession(hostId);
+ const [offer, setOffer] = useState();
+ const [failed, setFailed] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const load = async (): Promise => {
+ const client = session.client;
+ if (!client) return setFailed(true);
+ setBusy(true);
+ setFailed(false);
+ const result = await memberPairingOffer(client);
+ setBusy(false);
+ if (result.ok) setOffer(result.value);
+ else setFailed(true);
+ };
+ const mount = useMounted(() => {
+ void load();
+ return () => {};
+ }, [session.client]);
+ const expires =
+ offer === undefined
+ ? ''
+ : new Date(offer.expiresAt).toLocaleTimeString(undefined, {
+ hour: '2-digit',
+ minute: '2-digit',
+ });
+ return (
+
+ router.back()} />}
+ testID="member-pairing"
+ >
+
+
+
+ {copy.hint}
+
+ {offer ? (
+
+
+
+ ) : null}
+ {offer ? (
+
+ {copy.expires.replace('{time}', expires)}
+
+ ) : null}
+ {failed ? (
+
+ {copy.failed}
+
+ ) : null}
+
+
+
+
+ );
+}
diff --git a/apps/mobile/app/pair/_layout.tsx b/apps/mobile/app/pair/_layout.tsx
index f421b28123..dd86ae0c1f 100644
--- a/apps/mobile/app/pair/_layout.tsx
+++ b/apps/mobile/app/pair/_layout.tsx
@@ -10,6 +10,7 @@ export default function PairLayout() {
+
);
}
diff --git a/apps/mobile/app/pair/index.tsx b/apps/mobile/app/pair/index.tsx
index 33bea36c36..67dbb95a1f 100644
--- a/apps/mobile/app/pair/index.tsx
+++ b/apps/mobile/app/pair/index.tsx
@@ -69,6 +69,15 @@ export default function PairChoiceScreen() {
})
}
/>
+ router.push('/pair/team')}
+ />
();
+ const first = useRef(initialStep(typeof params.i === 'string' ? params.i : undefined));
+ const [step, setStep] = useState(first.current.step);
+ const [error, setError] = useState(first.current.error);
+ const [retryAfter, setRetryAfter] = useState();
+ const [busy, setBusy] = useState(false);
+ const [link, setLink] = 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 text = copy[code] ?? copy['generic']!;
+ return text.replace('{seconds}', String(retryAfter ?? 60));
+ };
+
+ const persist = async (host: SavedHost): Promise => {
+ let result = await hostSession.pairMember(host);
+ if (!result.ok && result.code === 'identity-switch-required') {
+ const confirmed = await new Promise((resolve) =>
+ Alert.alert(
+ t.teamSignIn.switchTitle,
+ t.teamSignIn.switchBody.replace('{name}', host.member?.displayName ?? ''),
+ [
+ { text: t.cancel, style: 'cancel', onPress: () => resolve(false) },
+ {
+ text: t.teamSignIn.switchConfirm,
+ style: 'destructive',
+ onPress: () => resolve(true),
+ },
+ ],
+ ),
+ );
+ if (!confirmed) return false;
+ result = await hostSession.pairMember(host, { confirmedIdentitySwitch: true });
+ }
+ if (!result.ok) {
+ setError(result.code);
+ return false;
+ }
+ return true;
+ };
+
+ const openLink = (): void => {
+ const parsed = parseTeamInvitation(link.trim());
+ if (!parsed.ok) {
+ setError(parsed.code);
+ return;
+ }
+ setError(undefined);
+ setStep({ kind: 'sign-in', invitation: parsed.value });
+ };
+
+ const signIn = async (invitation: TeamInvitation): Promise => {
+ setBusy(true);
+ setError(undefined);
+ const result = await signInTeamDevice({
+ carrier: nativeCarrier(),
+ invitation,
+ password,
+ deviceName: phoneName(),
+ });
+ setBusy(false);
+ if (!result.ok) {
+ setRetryAfter(result.retryAfterSeconds);
+ setError(result.code);
+ setPassword('');
+ return;
+ }
+ if (result.value.member?.mustChangePassword === true) {
+ setStep({ kind: 'change', host: result.value, current: password });
+ setPassword('');
+ return;
+ }
+ setBusy(true);
+ const saved = await persist(result.value);
+ setBusy(false);
+ if (saved) router.dismissTo('/');
+ };
+
+ const change = async (host: SavedHost, current: string): Promise => {
+ if (next.length < PASSWORD_MIN) return setError('password-weak');
+ if (next !== confirm) return setError('mismatch');
+ if (next === current) return setError('password-reused');
+ setBusy(true);
+ setError(undefined);
+ const result = await changeTeamDevicePassword({
+ carrier: nativeCarrier(),
+ host,
+ current,
+ next,
+ });
+ if (!result.ok) {
+ setBusy(false);
+ setRetryAfter(result.retryAfterSeconds);
+ setError(result.code);
+ return;
+ }
+ const saved = await persist(result.value);
+ setBusy(false);
+ if (saved) router.dismissTo('/');
+ };
+
+ const errorText =
+ error === undefined ? null : (
+
+ {message(error)}
+
+ );
+
+ return (
+
+ {step.kind === 'link' ? (
+ <>
+ {t.teamSignIn.linkHint}
+ {
+ setLink(value);
+ setError(undefined);
+ }}
+ placeholder="deepseekbot://team?i=…"
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ returnKeyType="go"
+ onSubmitEditing={openLink}
+ />
+ {errorText}
+
+ >
+ ) : step.kind === 'sign-in' ? (
+ <>
+
+
+ {t.teamSignIn.title.replace('{host}', step.invitation.host.name)}
+
+
+ {t.teamSignIn.as.replace('{username}', step.invitation.username)}
+
+
+ {
+ setPassword(value);
+ setError(undefined);
+ }}
+ secureTextEntry
+ textContentType="password"
+ autoComplete="current-password"
+ autoCapitalize="none"
+ autoCorrect={false}
+ returnKeyType="go"
+ editable={!busy}
+ onSubmitEditing={() => void signIn(step.invitation)}
+ />
+
+ {t.teamSignIn.passwordHint}
+
+ {errorText}
+
+ );
+}
diff --git a/apps/mobile/src/host/client.ts b/apps/mobile/src/host/client.ts
index 9854a808a5..5ee18109c0 100644
--- a/apps/mobile/src/host/client.ts
+++ b/apps/mobile/src/host/client.ts
@@ -1,3 +1,4 @@
+import type { HostMemberIdentity } from './member-identity';
import { readComputerAvailability } from './computer-availability';
import {
encryptedCarrier,
@@ -209,6 +210,7 @@ export interface HostApiAnswer {
}
export interface HostClientOptions {
+ member?: HostMemberIdentity;
routePreference?: string;
onRoutePreferenceChanged?: (route: string | undefined) => Promise;
onRoutesChanged?: (routes: string[]) => Promise;
@@ -378,6 +380,7 @@ export function arrangementOf(value: unknown): RosterArrangement | undefined {
export function createHostClient(options: HostClientOptions): HostClient {
const carrier = encryptedCarrier({
raw: options.carrier,
+ ...(options.member ? { trustedHttpsOrigins: options.routes } : {}),
hostId: options.hostId ?? '',
credential: options.credential,
...(options.encryption === undefined ? {} : { encryption: options.encryption }),
diff --git a/apps/mobile/src/host/encrypted-carrier.ts b/apps/mobile/src/host/encrypted-carrier.ts
index 85acd69fe3..78591540b0 100644
--- a/apps/mobile/src/host/encrypted-carrier.ts
+++ b/apps/mobile/src/host/encrypted-carrier.ts
@@ -11,7 +11,14 @@ import type {
HostSocketEvents,
} from './carrier';
import type { HostEncryption } from './hosts';
-import { checkRoute, hasPrivateOrigin, isEncryptedRoute, isLanRoute, socketOrigin } from './route';
+import {
+ checkRoute,
+ hasPrivateOrigin,
+ isConnectRoute,
+ isEncryptedRoute,
+ isLanRoute,
+ socketOrigin,
+} from './route';
import { APP_VERSION_HEADER } from '../../../../packages/core/src/devices/client-compat';
export const HOST_KEY_REJECTIONS: ReadonlySet = new Set([
@@ -25,14 +32,24 @@ export class ConnectRefused extends Error {
}
}
-function requestUrl(input: string, privateOrigin?: Parameters[1]): URL {
+function requestUrl(
+ input: string,
+ privateOrigin?: Parameters[1],
+ trustedHttpsOrigins: readonly string[] = [],
+): URL {
let url: URL;
try {
url = new URL(input);
} catch {
throw new ConnectRefused('route-invalid');
}
- if (!checkRoute(url.origin, privateOrigin).ok || url.username || url.password || url.hash)
+ if (
+ (!checkRoute(url.origin, privateOrigin).ok &&
+ !(url.protocol === 'https:' && trustedHttpsOrigins.includes(url.origin))) ||
+ url.username ||
+ url.password ||
+ url.hash
+ )
throw new ConnectRefused('route-invalid');
return url;
}
@@ -103,12 +120,20 @@ export function openNoiseSocket(options: {
origin: string;
hostId: string;
encryption: HostEncryption;
+ trustedHttpsOrigins?: readonly string[];
raw: HostCarrier;
timeoutMs?: number;
message(value: Record): void;
closed(reason: string): void;
}) {
- if (!checkRoute(options.origin, options.encryption.privateRelay).ok)
+ if (
+ !checkRoute(options.origin, options.encryption.privateRelay).ok &&
+ !(
+ options.trustedHttpsOrigins?.includes(options.origin) &&
+ new URL(options.origin).protocol === 'https:' &&
+ new URL(options.origin).origin === options.origin
+ )
+ )
throw new ConnectRefused('route-invalid');
const channel = new ConnectChannel({
role: 'initiator',
@@ -280,11 +305,20 @@ interface DirectRetry {
export function encryptedCarrier(options: {
requireEncryption?: boolean;
+ trustedHttpsOrigins?: readonly string[];
raw: HostCarrier;
hostId: string;
credential: string;
encryption?: HostEncryption;
}): HostCarrier {
+ const needsEncryption = (origin: string) =>
+ isEncryptedRoute(origin, options.encryption) &&
+ !(
+ options.trustedHttpsOrigins?.includes(origin) &&
+ !isConnectRoute(origin) &&
+ !isLanRoute(origin) &&
+ !options.encryption?.privateRelay
+ );
const sessions = new Map();
const directs = new Map();
const retries = new Map();
@@ -437,7 +471,13 @@ export function encryptedCarrier(options: {
};
const upgrade = (origin: string) => {
const openDirect = options.raw.openDirect;
- if (!openDirect || closedCarrier || isLanRoute(origin)) return;
+ if (
+ options.credential.startsWith('member.') ||
+ !openDirect ||
+ closedCarrier ||
+ isLanRoute(origin)
+ )
+ return;
const state = retryState(origin);
const relay = sessions.get(origin);
if (state.blocked || state.running || directs.has(origin) || !relay?.admitted) return;
@@ -481,7 +521,7 @@ export function encryptedCarrier(options: {
url: string,
init: HostRequest,
): Promise => {
- const parsed = requestUrl(url, options.encryption?.privateRelay);
+ const parsed = requestUrl(url, options.encryption?.privateRelay, options.trustedHttpsOrigins);
await waitForAdmission(current.ready, init.signal);
if (init.signal.aborted) throw new Error('request-cancelled');
if (
@@ -556,15 +596,19 @@ export function encryptedCarrier(options: {
directs.clear();
},
async request(url, init) {
- const parsed = requestUrl(url, options.encryption?.privateRelay);
- if (!options.requireEncryption && !isEncryptedRoute(parsed.origin, options.encryption))
+ const parsed = requestUrl(url, options.encryption?.privateRelay, options.trustedHttpsOrigins);
+ if (!options.requireEncryption && !needsEncryption(parsed.origin))
return options.raw.request(url, init);
if (init.signal.aborted) throw new Error('request-cancelled');
return relayRequest(pick(parsed.origin), url, init);
},
openSocket(url, events, headers): HostSocket {
- const parsed = requestUrl(url.replace(/^ws/u, 'http'), options.encryption?.privateRelay);
- if (!options.requireEncryption && !isEncryptedRoute(parsed.origin, options.encryption))
+ const parsed = requestUrl(
+ url.replace(/^ws/u, 'http'),
+ options.encryption?.privateRelay,
+ options.trustedHttpsOrigins,
+ );
+ if (!options.requireEncryption && !needsEncryption(parsed.origin))
return options.raw.openSocket(url, events, headers);
let current: Session | undefined,
done = false;
diff --git a/apps/mobile/src/host/host-session.ts b/apps/mobile/src/host/host-session.ts
index c5905e3a97..ee46bfdbed 100644
--- a/apps/mobile/src/host/host-session.ts
+++ b/apps/mobile/src/host/host-session.ts
@@ -1,3 +1,5 @@
+import type { TeamResult } from './team-invitation';
+import { identitySwitchRequired } from './member-identity';
import { hostStore, hostStoreAvailable } from './host-store';
import type { AccountOwner } from './account-owner';
import { removeAccountConnections } from './account-connections';
@@ -21,6 +23,7 @@ import {
conversationCache,
conversationCacheWaitMs,
forgetHostConversations,
+ clearHostConversations,
pruneHostConversations,
warmHostConversations,
} from './native-conversations';
@@ -440,6 +443,7 @@ function adopt(next: SavedHosts, trigger: ConnectionTrigger = 'open'): void {
const saved = next.hosts.find((host) => host.hostId === id);
if (
!saved ||
+ saved.member?.mustChangePassword ||
saved.credential !== session.host.saved.credential ||
JSON.stringify(saved.encryption) !== JSON.stringify(session.host.saved.encryption)
) {
@@ -449,6 +453,7 @@ function adopt(next: SavedHosts, trigger: ConnectionTrigger = 'open'): void {
}
}
for (const saved of next.hosts) {
+ if (saved.member?.mustChangePassword) continue;
const existing = sessions.get(saved.hostId);
if (existing) {
existing.host.saved = saved;
@@ -605,14 +610,61 @@ export const hostSession = {
feeds.find((host) => host.saved.hostId === hostId),
getSelectionRevision: (): number => selectionIntent,
getSourceChangeRevision: (): number => sourceChangeRevision,
- async pair(host: SavedHost): Promise {
+ async pair(host: SavedHost, options: { confirmedIdentitySwitch?: boolean } = {}): Promise {
selectionIntent++;
if (state.saved?.hostId !== host.hostId) sourceChangeRevision++;
return serialize(async () => {
- await commit(withHost(stored, host), 'pair');
+ const next = withHost(stored, host, options.confirmedIdentitySwitch === true);
+ const previous = stored.hosts.find((item) => item.hostId === host.hostId);
+ if (identitySwitchRequired(previous, host) && previous) {
+ const session = sessions.get(host.hostId);
+ sessions.delete(host.hostId);
+ session?.dispose();
+ await clearPresentations(previous);
+ try {
+ await sourceDrafts.ready;
+ await sourceDrafts.removePersistedWhere((key) => {
+ try {
+ const parts = JSON.parse(key);
+ return parts[0] === 'computer' && parts[1] === host.hostId;
+ } catch {
+ return false;
+ }
+ });
+ await clearHostConversations(host.hostId);
+ purgeCaches.forgetHost(host.hostId);
+ await forgetRecentChats(host.hostId);
+ await conversationFilter.clearPersisted(computerEnvironmentKey(host.hostId));
+ } catch (error) {
+ adopt(stored);
+ throw error;
+ }
+ }
+ try {
+ await commit(next, 'pair');
+ } catch (error) {
+ adopt(stored);
+ throw error;
+ }
void pushSession.enable(stored.hosts);
});
},
+ async pairMember(
+ host: SavedHost,
+ options: { confirmedIdentitySwitch?: boolean } = {},
+ ): Promise> {
+ if (!host.member) return { ok: false, code: 'credentials-invalid' };
+ try {
+ await hostSession.pair(host, options);
+ return { ok: true, value: host };
+ } catch (error) {
+ const code = error instanceof Error ? error.message : '';
+ if (code === 'identity-switch-required') return { ok: false, code };
+ if (code === 'fingerprint-mismatch' || code === 'host-key-mismatch')
+ return { ok: false, code: 'fingerprint-mismatch' };
+ return { ok: false, code: 'storage-failed' };
+ }
+ },
async switchTo(hostId: string, current: () => boolean = () => true): Promise {
const intent = ++selectionIntent;
const ownsSelection = () => current() && intent === selectionIntent;
diff --git a/apps/mobile/src/host/hosts.ts b/apps/mobile/src/host/hosts.ts
index 284891dbdf..75ece1cdf6 100644
--- a/apps/mobile/src/host/hosts.ts
+++ b/apps/mobile/src/host/hosts.ts
@@ -1,3 +1,9 @@
+import {
+ parseHostMemberIdentity,
+ identitySwitchRequired,
+ hostIdentityMatches,
+ type HostMemberIdentity,
+} from './member-identity';
import { parseAccountOwner, type AccountOwner } from './account-owner';
import { hasPrivateOrigin, isPrivateRoute } from './route';
@@ -16,6 +22,7 @@ export interface HostEncryption {
}
export interface SavedHost {
+ member?: HostMemberIdentity;
relationshipId?: string;
routePreference?: string;
accountOwner?: AccountOwner;
@@ -48,6 +55,14 @@ export function parseSavedHost(input: unknown): SavedHost | undefined {
return undefined;
if (value['routePreference'] !== undefined && typeof value['routePreference'] !== 'string')
return undefined;
+ const member = parseHostMemberIdentity(value['member']);
+ if (value['member'] !== undefined && !member) return undefined;
+ if (
+ typeof value['credential'] === 'string' &&
+ value['credential'].startsWith('member.') &&
+ !member
+ )
+ return undefined;
const privateRelay = parsePrivateAdmission(record(value['encryption'])['privateRelay']);
if (record(value['encryption'])['privateRelay'] !== undefined && !privateRelay) return;
if (
@@ -101,6 +116,7 @@ export function parseSavedHost(input: unknown): SavedHost | undefined {
...(parseEncryption(value['encryption']) === undefined
? {}
: { encryption: parseEncryption(value['encryption'])! }),
+ ...(member ? { member } : {}),
hostId: value['hostId'],
hostName: value['hostName'],
routes: (encryptedRoutes ?? value['routes']) as string[],
@@ -149,7 +165,7 @@ export function parseSavedHosts(
? value['pendingAccountRemoval'].flatMap((entry) => parseSavedHost(entry) ?? [])
: [];
return {
- hosts,
+ hosts: [...new Map(hosts.map((host) => [host.hostId, host])).values()],
...(current === undefined ? {} : { current }),
...(pendingAccountRemoval.length ? { pendingAccountRemoval } : {}),
};
@@ -159,12 +175,19 @@ export function currentHost(state: SavedHosts): SavedHost | undefined {
return state.hosts.find((host) => host.hostId === state.current);
}
-export function withHost(state: SavedHosts, host: SavedHost): SavedHosts {
+export function withHost(
+ state: SavedHosts,
+ host: SavedHost,
+ confirmedIdentitySwitch = false,
+): SavedHosts {
if (state.pendingAccountRemoval?.some((entry) => entry.hostId === host.hostId))
throw new Error('account-cleanup-pending');
const previous = state.hosts.find((entry) => entry.hostId === host.hostId);
if (previous?.encryption && previous.encryption.hostKey !== host.encryption?.hostKey)
throw new Error('host-key-mismatch');
+ if (!hostIdentityMatches(previous, host)) throw new Error('fingerprint-mismatch');
+ if (identitySwitchRequired(previous, host) && !confirmedIdentitySwitch)
+ throw new Error('identity-switch-required');
return {
...state,
diff --git a/apps/mobile/src/host/member-identity.ts b/apps/mobile/src/host/member-identity.ts
new file mode 100644
index 0000000000..f73c66398d
--- /dev/null
+++ b/apps/mobile/src/host/member-identity.ts
@@ -0,0 +1,89 @@
+import { noiseFingerprint } from '../../../../packages/core/src/devices/noise/xk';
+import { teamRecord, type TeamResult } from './team-invitation';
+import type { SavedHost, SavedHosts } from './hosts';
+
+export interface HostMemberIdentity {
+ humanId: string;
+ displayName: string;
+ username: string;
+ fingerprint: string;
+ mustChangePassword: boolean;
+}
+export function parseHostMemberIdentity(input: unknown): HostMemberIdentity | undefined {
+ const value = teamRecord(input);
+ return typeof value['humanId'] === 'string' &&
+ value['humanId'].length > 0 &&
+ typeof value['displayName'] === 'string' &&
+ typeof value['username'] === 'string' &&
+ typeof value['fingerprint'] === 'string' &&
+ /^(?:[a-f0-9]{64}|(?:[a-f0-9]{4} ){15}[a-f0-9]{4})$/u.test(value['fingerprint']) &&
+ typeof value['mustChangePassword'] === 'boolean'
+ ? {
+ humanId: value['humanId'],
+ displayName: value['displayName'],
+ username: value['username'],
+ fingerprint: value['fingerprint'],
+ mustChangePassword: value['mustChangePassword'],
+ }
+ : undefined;
+}
+export type PasswordGateState =
+ | { kind: 'loading' }
+ | { kind: 'signed-out' }
+ | { kind: 'owner' }
+ | { kind: 'password-change-required'; host: SavedHost; member: HostMemberIdentity }
+ | { kind: 'ready'; host: SavedHost; member: HostMemberIdentity };
+export function memberPasswordGate(host: SavedHost | null | undefined): PasswordGateState {
+ if (host === undefined) return { kind: 'loading' };
+ if (host === null) return { kind: 'signed-out' };
+ if (!host.member) return { kind: 'owner' };
+ return {
+ kind: host.member.mustChangePassword ? 'password-change-required' : 'ready',
+ host,
+ member: host.member,
+ };
+}
+export function identitySwitchRequired(previous: SavedHost | undefined, next: SavedHost): boolean {
+ return (
+ previous !== undefined &&
+ previous.hostId === next.hostId &&
+ (previous.member?.humanId ?? 'local-human') !== (next.member?.humanId ?? 'local-human')
+ );
+}
+export function hostIdentityMatches(previous: SavedHost | undefined, next: SavedHost): boolean {
+ const fingerprint = (host: SavedHost | undefined) => {
+ if (host?.member) return host.member.fingerprint;
+ const key = host?.encryption?.hostKey;
+ if (!key || !/^[a-f0-9]{64}$/u.test(key)) return undefined;
+ return noiseFingerprint(
+ Uint8Array.from(key.match(/../gu)!, (byte) => Number.parseInt(byte, 16)),
+ );
+ };
+ const pinned = fingerprint(previous);
+ return pinned === undefined || pinned === fingerprint(next);
+}
+export function prepareMemberIdentity(
+ state: SavedHosts,
+ host: SavedHost,
+ confirmed = false,
+): TeamResult {
+ const previous = state.hosts.find((item) => item.hostId === host.hostId);
+ if (!hostIdentityMatches(previous, host)) return { ok: false, code: 'fingerprint-mismatch' };
+ if (identitySwitchRequired(previous, host) && !confirmed)
+ return { ok: false, code: 'identity-switch-required' };
+ return { ok: true, value: host };
+}
+
+export function pairedMemberIdentity(
+ input: unknown,
+ fingerprint: string,
+): HostMemberIdentity | undefined {
+ const value = teamRecord(input);
+ return parseHostMemberIdentity({
+ humanId: value['humanId'],
+ displayName: value['displayName'],
+ mustChangePassword: value['mustChangePassword'],
+ username: '',
+ fingerprint,
+ });
+}
diff --git a/apps/mobile/src/host/pairing.ts b/apps/mobile/src/host/pairing.ts
index 812a823e9c..6f1ec95721 100644
--- a/apps/mobile/src/host/pairing.ts
+++ b/apps/mobile/src/host/pairing.ts
@@ -1,3 +1,5 @@
+import { teamHttpsRoute } from './team-invitation';
+import { pairedMemberIdentity } from './member-identity';
import type { ConnectionDiagnostic } from './connection-diagnostic';
import { noiseFingerprint, noisePublicKey } from '../../../../packages/core/src/devices/noise/xk';
import {
@@ -27,6 +29,7 @@ import { learnedRoutes } from './learned-routes';
export const DEVICE_PREFIX = '/botharness-device';
export interface PairingPayload {
+ member?: true;
enrollment?: { body: string; signature: string };
encryption?: {
protocol: 'connect-noise-xk-v1';
@@ -138,12 +141,19 @@ export function parsePairingLink(text: string, now = Date.now()): ParsedLink {
parsePrivateAdmission(record(value['encryption'])['privateRelay'])?.origin,
)
: undefined;
- return checked?.ok === true ? [checked.origin] : [];
+ return checked?.ok === true
+ ? [checked.origin]
+ : value['member'] === true &&
+ teamHttpsRoute(route) &&
+ record(value['encryption'])['protocol'] === 'connect-noise-xk-v1'
+ ? [new URL(route).origin]
+ : [];
});
if (routes.length === 0) return { ok: false, code: 'no-route' };
return {
ok: true,
payload: {
+ ...(value['member'] === true ? { member: true as const } : {}),
host: { id: host['id'], name: host['name'] },
offer: value['offer'],
routes,
@@ -196,7 +206,11 @@ export async function redeemPairing(options: {
return { ok: false, code: 'no-route' };
if (
payload.routes.length === 0 ||
- payload.routes.some((route) => !checkRoute(route, payload.encryption?.privateRelay).ok)
+ payload.routes.some(
+ (route) =>
+ !checkRoute(route, payload.encryption?.privateRelay).ok &&
+ !(payload.member && payload.encryption && teamHttpsRoute(route)),
+ )
)
return { ok: false, code: 'no-route' };
if (payload.enrollment && payload.routes.some((route) => !isConnectRoute(route)))
@@ -397,9 +411,10 @@ export async function pairHost(options: {
return parsed;
}
const existing = options.existing?.(parsed.payload.host.id);
- const updated = existing?.encryption
- ? await updatePairedRoutes(existing, parsed.payload, options.carrier, options.signal)
- : undefined;
+ const updated =
+ !parsed.payload.member && existing?.encryption
+ ? await updatePairedRoutes(existing, parsed.payload, options.carrier, options.signal)
+ : undefined;
const redeemed =
updated && (updated.ok || updated.code !== 'reapproval-required')
? updated
@@ -686,6 +701,7 @@ function redeemEncryptedRoute(
};
const socket = openNoiseSocket({
origin: route,
+ ...(payload.member ? { trustedHttpsOrigins: payload.routes } : {}),
hostId: payload.host.id,
encryption,
raw: options.carrier,
@@ -717,6 +733,14 @@ function redeemEncryptedRoute(
],
deviceId: value['deviceId'],
credential: value['credential'],
+ ...(pairedMemberIdentity(value, noiseFingerprint(keyBytes(encryption.hostKey)))
+ ? {
+ member: pairedMemberIdentity(
+ value,
+ noiseFingerprint(keyBytes(encryption.hostKey)),
+ )!,
+ }
+ : {}),
encryption,
},
});
diff --git a/apps/mobile/src/host/team-client.ts b/apps/mobile/src/host/team-client.ts
new file mode 100644
index 0000000000..54531565eb
--- /dev/null
+++ b/apps/mobile/src/host/team-client.ts
@@ -0,0 +1,330 @@
+import type { HostCarrier } from './carrier';
+import type { HostEncryption, SavedHost } from './hosts';
+import {
+ ConnectRefused,
+ encryptedCarrier,
+ keyBytes,
+ keyHex,
+ openNoiseSocket,
+ secureRandom,
+} from './encrypted-carrier';
+import { isConnectRoute } from './route';
+import { noiseFingerprint } from '../../../../packages/core/src/devices/noise/xk';
+import {
+ parseTeamInvitation,
+ teamHostIdentity,
+ teamHttpsRoute,
+ teamRecord,
+ type TeamErrorCode,
+ type TeamHostIdentity,
+ type TeamInvitation,
+ type TeamResult,
+} from './team-invitation';
+
+export { parseTeamInvitation } from './team-invitation';
+export type { TeamInvitation, TeamErrorCode, TeamResult } from './team-invitation';
+export { memberPasswordGate, prepareMemberIdentity } from './member-identity';
+
+const codes: ReadonlySet = new Set([
+ 'credentials-invalid',
+ 'rate-limited',
+ 'insecure-transport',
+ 'team-mode-off',
+ 'member-suspended',
+ 'fingerprint-mismatch',
+ 'password-change-required',
+ 'password-weak',
+ 'password-reused',
+ 'invalid-input',
+ 'remote-access/denied',
+]);
+function refusal(value: unknown): TeamResult {
+ const input = teamRecord(value);
+ const code = input['code'];
+ const known =
+ typeof code === 'string' && codes.has(code) ? (code as TeamErrorCode) : 'response-invalid';
+ return {
+ ok: false,
+ code: known,
+ ...(typeof input['retryAfterSeconds'] === 'number' &&
+ Number.isFinite(input['retryAfterSeconds']) &&
+ input['retryAfterSeconds'] > 0
+ ? { retryAfterSeconds: input['retryAfterSeconds'] }
+ : {}),
+ };
+}
+function requestFailure(error: unknown, signal: AbortSignal): TeamResult {
+ if (signal.aborted) return { ok: false, code: 'request-cancelled' };
+ if (
+ error instanceof ConnectRefused &&
+ ['channel-authentication-failed', 'channel-handshake-rejected'].includes(error.code)
+ )
+ return { ok: false, code: 'fingerprint-mismatch' };
+ return { ok: false, code: 'unreachable' };
+}
+function signedHost(
+ input: unknown,
+ invitation: TeamInvitation,
+ route: string,
+ encryption: HostEncryption,
+): TeamResult {
+ const value = teamRecord(input);
+ const host = teamHostIdentity(value['host']);
+ if (!host || host.id !== invitation.host.id || host.fingerprint !== invitation.host.fingerprint)
+ return { ok: false, code: 'fingerprint-mismatch' };
+ if (
+ typeof value['deviceId'] !== 'string' ||
+ typeof value['credential'] !== 'string' ||
+ !/^member\.[A-Za-z0-9_-]{43}$/u.test(value['credential']) ||
+ typeof value['humanId'] !== 'string' ||
+ !value['humanId'] ||
+ typeof value['displayName'] !== 'string' ||
+ typeof value['mustChangePassword'] !== 'boolean'
+ )
+ return { ok: false, code: 'response-invalid' };
+ return {
+ ok: true,
+ value: {
+ hostId: host.id,
+ hostName: host.name,
+ routes: [route, ...invitation.routes.filter((item) => item !== route)],
+ deviceId: value['deviceId'],
+ credential: value['credential'],
+ encryption,
+ member: {
+ humanId: value['humanId'],
+ displayName: value['displayName'],
+ username: invitation.username,
+ fingerprint: host.fingerprint,
+ mustChangePassword: value['mustChangePassword'],
+ },
+ },
+ };
+}
+async function encryptedSignIn(options: {
+ carrier: HostCarrier;
+ route: string;
+ host: TeamHostIdentity;
+ encryption: HostEncryption;
+ input: unknown;
+ signal: AbortSignal;
+}): Promise> {
+ return new Promise((resolve) => {
+ let done = false;
+ let socket: ReturnType | undefined;
+ const finish = (result: TeamResult) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ options.signal.removeEventListener('abort', abort);
+ resolve(result);
+ socket?.close();
+ };
+ const abort = () => finish({ ok: false, code: 'request-cancelled' });
+ const timer = setTimeout(() => finish({ ok: false, code: 'unreachable' }), 30_000);
+ options.signal.addEventListener('abort', abort, { once: true });
+ if (options.signal.aborted) {
+ abort();
+ return;
+ }
+ try {
+ socket = openNoiseSocket({
+ origin: options.route,
+ hostId: options.host.id,
+ encryption: options.encryption,
+ raw: options.carrier,
+ closed: (reason) => finish(requestFailure(new ConnectRefused(reason), options.signal)),
+ message: (frame) => {
+ if (frame['type'] !== 'team-signed-in') return;
+ const result = teamRecord(frame['result']);
+ finish(result['ok'] === true ? { ok: true, value: result['value'] } : refusal(result));
+ },
+ });
+ void socket.ready.then(
+ () => {
+ if (!done) socket?.send({ type: 'team-sign-in', input: options.input });
+ },
+ (error) => finish(requestFailure(error, options.signal)),
+ );
+ } catch (error) {
+ finish(requestFailure(error, options.signal));
+ }
+ });
+}
+
+export interface TeamDeviceSignInOptions {
+ carrier: HostCarrier;
+ invitation: TeamInvitation;
+ password: string;
+ deviceName: string;
+ route?: string;
+ signal?: AbortSignal;
+ now?: number;
+}
+export async function signInTeamDevice(
+ options: TeamDeviceSignInOptions,
+): Promise> {
+ const parsed = parseTeamInvitation(
+ `deepseekbot://team?i=${encodeInvitation(options.invitation)}`,
+ options.now ?? Date.now(),
+ );
+ if (!parsed.ok) return parsed;
+ const invitation = parsed.value;
+ const routes = options.route === undefined ? invitation.routes : [options.route];
+ if (
+ !routes.length ||
+ routes.some((route) => !teamHttpsRoute(route) || !invitation.routes.includes(route))
+ )
+ return { ok: false, code: 'insecure-transport' };
+ const signal = options.signal
+ ? AbortSignal.any([options.signal, AbortSignal.timeout(30_000)])
+ : AbortSignal.timeout(30_000);
+ for (const route of routes) {
+ if (signal.aborted) return { ok: false, code: 'request-cancelled' };
+ const attemptSignal = AbortSignal.any([signal, AbortSignal.timeout(8_000)]);
+ const result = await signInTeamRoute({ ...options, invitation, route, signal: attemptSignal });
+ if (result.ok) return result;
+ if (result.code !== 'unreachable' && !(result.code === 'request-cancelled' && !signal.aborted))
+ return result;
+ }
+ return { ok: false, code: 'unreachable' };
+}
+async function signInTeamRoute(
+ options: TeamDeviceSignInOptions & { route: string; signal: AbortSignal },
+): Promise> {
+ const { invitation, route, signal } = options;
+ try {
+ const response = await options.carrier.request(`${route}/botharness-device/channel`, {
+ method: 'GET',
+ signal,
+ });
+ if (response.status !== 200) return { ok: false, code: 'unreachable' };
+ const discovery = teamRecord(JSON.parse(await response.text()));
+ const host = teamRecord(discovery['host']);
+ const remote = teamRecord(discovery['encryption']);
+ const publicKey = remote['publicKey'];
+ if (
+ host['id'] !== invitation.host.id ||
+ typeof publicKey !== 'string' ||
+ !/^[a-f0-9]{64}$/u.test(publicKey) ||
+ noiseFingerprint(keyBytes(publicKey)) !== invitation.host.fingerprint ||
+ remote['fingerprint'] !== invitation.host.fingerprint
+ )
+ return { ok: false, code: 'fingerprint-mismatch' };
+ const encryption: HostEncryption = {
+ protocol: 'connect-noise-xk-v1',
+ hostKey: publicKey,
+ deviceKey: keyHex(secureRandom(options.carrier)),
+ };
+ const input = {
+ username: invitation.username,
+ password: options.password,
+ deviceName: options.deviceName,
+ fingerprint: invitation.host.fingerprint,
+ };
+ if (isConnectRoute(route)) {
+ const result = await encryptedSignIn({
+ ...options,
+ route,
+ host: invitation.host,
+ encryption,
+ input,
+ signal,
+ });
+ return result.ok ? signedHost(result.value, invitation, route, encryption) : result;
+ }
+ const result = await options.carrier.request(`${route}/botharness-device/team/device-sign-in`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ signal,
+ headers: { 'content-type': 'application/json' },
+ });
+ const value: unknown = JSON.parse(await result.text());
+ return result.status === 200
+ ? signedHost(value, invitation, route, encryption)
+ : refusal(value);
+ } catch (error) {
+ return requestFailure(error, signal);
+ }
+}
+function encodeInvitation(value: TeamInvitation): string {
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
+}
+
+export async function changeTeamDevicePassword(options: {
+ carrier: HostCarrier;
+ host: SavedHost;
+ current: string;
+ next: string;
+ signal?: AbortSignal;
+}): Promise> {
+ if (!options.host.member) return { ok: false, code: 'credentials-invalid' };
+ const route = options.host.routes[0];
+ if (!route || !teamHttpsRoute(route)) return { ok: false, code: 'insecure-transport' };
+ const signal = options.signal
+ ? AbortSignal.any([options.signal, AbortSignal.timeout(30_000)])
+ : AbortSignal.timeout(30_000);
+ const carrier = encryptedCarrier({
+ raw: options.carrier,
+ hostId: options.host.hostId,
+ credential: options.host.credential,
+ trustedHttpsOrigins: options.host.routes,
+ ...(options.host.encryption ? { encryption: options.host.encryption } : {}),
+ });
+ try {
+ const response = await carrier.request(`${route}/botharness-device/team/device-password`, {
+ method: 'POST',
+ headers: {
+ authorization: `Device ${options.host.credential}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ current: options.current, next: options.next }),
+ signal,
+ });
+ if (response.status !== 200) return refusal(JSON.parse(await response.text()));
+ return {
+ ok: true,
+ value: { ...options.host, member: { ...options.host.member, mustChangePassword: false } },
+ };
+ } catch (error) {
+ return requestFailure(error, signal);
+ } finally {
+ carrier.close?.();
+ }
+}
+export interface MemberPairingOffer {
+ link: string;
+ qr: { size: number; path: string };
+ expiresAt: string;
+ receipt: string;
+}
+export async function memberPairingOffer(client: {
+ call(method: string): Promise;
+}): Promise> {
+ try {
+ const value = teamRecord(await client.call('memberPairingOffer'));
+ const qr = teamRecord(value['qr']);
+ if (
+ typeof value['link'] !== 'string' ||
+ typeof value['expiresAt'] !== 'string' ||
+ typeof value['receipt'] !== 'string' ||
+ typeof qr['size'] !== 'number' ||
+ typeof qr['path'] !== 'string'
+ )
+ return { ok: false, code: 'response-invalid' };
+ return {
+ ok: true,
+ value: {
+ link: value['link'],
+ expiresAt: value['expiresAt'],
+ receipt: value['receipt'],
+ qr: { size: qr['size'], path: qr['path'] },
+ },
+ };
+ } catch (error) {
+ return refusal(error);
+ }
+}
diff --git a/apps/mobile/src/host/team-invitation.ts b/apps/mobile/src/host/team-invitation.ts
new file mode 100644
index 0000000000..32e9f5bf50
--- /dev/null
+++ b/apps/mobile/src/host/team-invitation.ts
@@ -0,0 +1,135 @@
+export interface TeamHostIdentity {
+ id: string;
+ name: string;
+ fingerprint: string;
+}
+export interface TeamInvitation {
+ v: 1;
+ host: TeamHostIdentity;
+ routes: string[];
+ username: string;
+ expiresAt: string;
+}
+export type InvitationError =
+ | 'invitation-invalid'
+ | 'invitation-expired'
+ | 'invitation-version-unsupported';
+export type TeamResult =
+ | { ok: true; value: T }
+ | { ok: false; code: E; retryAfterSeconds?: number };
+export type TeamErrorCode =
+ | InvitationError
+ | 'credentials-invalid'
+ | 'rate-limited'
+ | 'insecure-transport'
+ | 'team-mode-off'
+ | 'member-suspended'
+ | 'fingerprint-mismatch'
+ | 'password-change-required'
+ | 'password-weak'
+ | 'password-reused'
+ | 'invalid-input'
+ | 'unreachable'
+ | 'response-invalid'
+ | 'request-cancelled'
+ | 'identity-switch-required'
+ | 'storage-failed'
+ | 'remote-access/denied';
+export function teamRecord(value: unknown): Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as Record)
+ : {};
+}
+export function teamHostIdentity(value: unknown): TeamHostIdentity | undefined {
+ const host = teamRecord(value);
+ return typeof host['id'] === 'string' &&
+ host['id'].length > 0 &&
+ host['id'].length <= 128 &&
+ typeof host['name'] === 'string' &&
+ host['name'].length <= 256 &&
+ typeof host['fingerprint'] === 'string' &&
+ /^(?:[a-f0-9]{64}|(?:[a-f0-9]{4} ){15}[a-f0-9]{4})$/u.test(host['fingerprint'])
+ ? { id: host['id'], name: host['name'], fingerprint: host['fingerprint'] }
+ : undefined;
+}
+export function teamHttpsRoute(value: unknown): value is string {
+ if (typeof value !== 'string' || value.length > 2048) return false;
+ try {
+ const url = new URL(value);
+ const name = url.hostname
+ .replace(/^\[|\]$/gu, '')
+ .replace(/\.$/u, '')
+ .toLowerCase();
+ return (
+ url.protocol === 'https:' &&
+ !url.username &&
+ !url.password &&
+ !url.hash &&
+ !url.search &&
+ !['localhost', '::1', '::', '0.0.0.0'].includes(name) &&
+ !name.endsWith('.localhost') &&
+ !/^(?:127|0)\./u.test(name) &&
+ !name.startsWith('::ffff:7f') &&
+ !name.startsWith('::ffff:0:')
+ );
+ } catch {
+ return false;
+ }
+}
+export function parseTeamInvitation(
+ link: string,
+ now = Date.now(),
+): TeamResult {
+ if (link.length > 16_384) return { ok: false, code: 'invitation-invalid' };
+ try {
+ const url = new URL(link.trim());
+ const encoded = url.searchParams.get('i');
+ if (
+ url.protocol !== 'deepseekbot:' ||
+ url.hostname !== 'team' ||
+ (url.pathname !== '' && url.pathname !== '/') ||
+ url.hash ||
+ url.username ||
+ url.password ||
+ url.port ||
+ [...url.searchParams.keys()].some((key) => key !== 'i') ||
+ url.searchParams.getAll('i').length !== 1 ||
+ !encoded ||
+ !/^[A-Za-z0-9_-]+$/u.test(encoded)
+ )
+ return { ok: false, code: 'invitation-invalid' };
+ const bytes = Uint8Array.from(atob(encoded.replace(/-/gu, '+').replace(/_/gu, '/')), (char) =>
+ char.charCodeAt(0),
+ );
+ const value = teamRecord(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
+ if (value['v'] !== 1) return { ok: false, code: 'invitation-version-unsupported' };
+ const host = teamHostIdentity(value['host']);
+ const routes = value['routes'];
+ const username = value['username'];
+ const expiresAt = value['expiresAt'];
+ if (
+ !host ||
+ !Array.isArray(routes) ||
+ routes.length > 16 ||
+ !routes.every(teamHttpsRoute) ||
+ typeof username !== 'string' ||
+ !/^[a-z0-9][a-z0-9._-]{1,31}$/u.test(username) ||
+ typeof expiresAt !== 'string' ||
+ !Number.isFinite(Date.parse(expiresAt))
+ )
+ return { ok: false, code: 'invitation-invalid' };
+ if (Date.parse(expiresAt) <= now) return { ok: false, code: 'invitation-expired' };
+ return {
+ ok: true,
+ value: {
+ v: 1,
+ host,
+ routes: [...new Set(routes.map((route) => new URL(route).origin))],
+ username,
+ expiresAt,
+ },
+ };
+ } catch {
+ return { ok: false, code: 'invitation-invalid' };
+ }
+}
diff --git a/apps/mobile/src/ui/design/tokens.ts b/apps/mobile/src/ui/design/tokens.ts
index a108a1d84a..fdd3cf76b5 100644
--- a/apps/mobile/src/ui/design/tokens.ts
+++ b/apps/mobile/src/ui/design/tokens.ts
@@ -508,3 +508,5 @@ export const signInBrand = {
googleMark: { red: '#ea4335', blue: '#4285f4', yellow: '#fbbc05', green: '#34a853' },
appIcon: 64,
} as const;
+
+export const qrCode = { ink: '#000000', paper: '#ffffff' } as const;
diff --git a/apps/mobile/src/ui/strings.ts b/apps/mobile/src/ui/strings.ts
index 2b9cee423e..02016e7748 100644
--- a/apps/mobile/src/ui/strings.ts
+++ b/apps/mobile/src/ui/strings.ts
@@ -1125,6 +1125,55 @@ const en = {
back: 'Back',
step: (index: number, total: number) => `step ${index} of ${total}`,
},
+ memberPairing: {
+ title: 'Pair another device',
+ hint: 'Scan this code with your other phone to sign it in as you. No password needed.',
+ qrLabel: 'Pairing code',
+ expires: 'Works once, until {time}.',
+ refresh: 'New code',
+ failed: 'Could not create a pairing code. Try again.',
+ signedInAs: 'Signed in as {name}',
+ pairAnother: 'Pair another device',
+ pairAnotherDetail: 'Use this account on another phone.',
+ },
+ teamSignIn: {
+ link: 'Invitation link',
+ linkHint:
+ 'Paste the invitation link from your Host owner. The password is sent to you separately.',
+ continue: 'Continue',
+ title: 'Sign in to {host}',
+ as: 'As {username}',
+ password: 'One-time password',
+ passwordHint: 'Use the password your Host owner gave you.',
+ signIn: 'Sign in',
+ changeTitle: 'Choose a new password',
+ changeHint: 'Replace the one-time password before you continue.',
+ newPassword: 'New password',
+ confirmPassword: 'Confirm new password',
+ rule: 'At least {min} characters.',
+ switchTitle: 'Switch account on this Host?',
+ switchBody:
+ "This phone will sign in as {name}. The other account's chats and drafts on this phone are removed.",
+ switchConfirm: 'Switch',
+ errors: {
+ generic: 'Could not sign in. Try again.',
+ 'invitation-invalid': 'This invitation link is not valid.',
+ 'invitation-expired': 'This invitation has expired. Ask for a new one.',
+ 'invitation-version-unsupported': 'Update the app to use this invitation.',
+ 'credentials-invalid': 'Wrong password.',
+ 'rate-limited': 'Too many attempts. Try again in {seconds} s.',
+ 'insecure-transport':
+ 'This Host cannot accept sign-in over this address. Ask for its HTTPS address.',
+ 'team-mode-off': 'This Host does not accept member sign-in right now.',
+ 'member-suspended': 'Your account is suspended. Ask the Host owner.',
+ 'fingerprint-mismatch': 'This Host does not match the invitation. Do not sign in.',
+ 'password-weak': 'Use at least 10 characters.',
+ 'password-reused': 'Choose a password you have not used here.',
+ 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.',
+ } as Record,
+ },
pairChoice: {
private: 'Private connection',
privateDetail: 'Recommended. No account or Docker needed.',
@@ -1142,6 +1191,8 @@ const en = {
accountDetail: 'Pick a computer on your account.',
lan: 'Use the same Wi-Fi',
lanDetail: 'Scan a code. No account needed.',
+ team: 'Join with an invitation',
+ teamDetail: "Sign in as a member of someone else's Host.",
tailscale: 'Use Tailscale',
tailscaleDetail: 'Connect across networks.',
tailscaleHint: 'Sign in to the same Tailscale account on both devices.',
@@ -3620,6 +3671,52 @@ const zh: typeof en = {
back: '上一步',
step: (index: number, total: number) => `第 ${index} 步,共 ${total} 步`,
},
+ memberPairing: {
+ title: '配对其他设备',
+ hint: '用你的另一台手机扫描此码,以你的身份登录,不需要密码。',
+ qrLabel: '配对码',
+ expires: '只能使用一次,{time} 前有效。',
+ refresh: '新配对码',
+ failed: '无法生成配对码,再试一次。',
+ signedInAs: '已登录为 {name}',
+ pairAnother: '配对其他设备',
+ pairAnotherDetail: '在另一台手机上使用此账号。',
+ },
+ teamSignIn: {
+ link: '邀请链接',
+ linkHint: '粘贴 Host 所有者发给你的邀请链接。密码会单独告诉你。',
+ continue: '继续',
+ title: '登录到 {host}',
+ as: '账号 {username}',
+ password: '一次性密码',
+ passwordHint: '使用 Host 所有者给你的密码。',
+ signIn: '登录',
+ changeTitle: '设置新密码',
+ changeHint: '继续之前,先替换一次性密码。',
+ newPassword: '新密码',
+ confirmPassword: '确认新密码',
+ rule: '至少 {min} 个字符。',
+ switchTitle: '在此 Host 上切换账号?',
+ switchBody: '这台手机将以 {name} 登录。另一个账号在本机的聊天和草稿会被移除。',
+ switchConfirm: '切换',
+ errors: {
+ generic: '登录失败,再试一次。',
+ 'invitation-invalid': '邀请链接无效。',
+ 'invitation-expired': '邀请已过期,请索取新的邀请。',
+ 'invitation-version-unsupported': '更新 App 后才能使用此邀请。',
+ 'credentials-invalid': '密码错误。',
+ 'rate-limited': '尝试次数太多,{seconds} 秒后再试。',
+ 'insecure-transport': '此 Host 无法通过该地址登录,请索取 HTTPS 地址。',
+ 'team-mode-off': '此 Host 暂不接受成员登录。',
+ 'member-suspended': '你的账号已停用,请联系 Host 所有者。',
+ 'fingerprint-mismatch': '此 Host 与邀请不符,请勿登录。',
+ 'password-weak': '至少使用 10 个字符。',
+ 'password-reused': '换一个在这里没用过的密码。',
+ mismatch: '两次输入的密码不一致。',
+ unreachable: '无法连接 Host,检查网络后再试。',
+ 'storage-failed': '无法在本机保存登录,再试一次。',
+ } as Record,
+ },
pairChoice: {
private: '私有连接',
privateDetail: '推荐。不需要账号或 Docker。',
@@ -3630,6 +3727,8 @@ const zh: typeof en = {
accountDetail: '选择账号下的电脑。',
lan: '使用同一 Wi-Fi',
lanDetail: '扫码即连,不需要账号。',
+ team: '使用邀请加入',
+ teamDetail: '以成员身份登录他人的 Host。',
tailscale: '使用 Tailscale',
tailscaleDetail: '跨网络连接。',
tailscaleHint: '两台设备登录同一个 Tailscale 账号。',
diff --git a/apps/mobile/test/team-members.test.ts b/apps/mobile/test/team-members.test.ts
new file mode 100644
index 0000000000..951a4293a8
--- /dev/null
+++ b/apps/mobile/test/team-members.test.ts
@@ -0,0 +1,328 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { randomBytes } from 'node:crypto';
+import { parseTeamInvitation, type TeamInvitation } from '../src/host/team-invitation';
+import {
+ changeTeamDevicePassword,
+ signInTeamDevice,
+ memberPairingOffer,
+} from '../src/host/team-client';
+import {
+ memberPasswordGate,
+ prepareMemberIdentity,
+ identitySwitchRequired,
+} from '../src/host/member-identity';
+import { parseSavedHosts, withHost, type SavedHost } from '../src/host/hosts';
+import type { HostCarrier } from '../src/host/carrier';
+import { noiseFingerprint, noisePublicKey } from '../../../packages/core/src/devices/noise/xk';
+
+const secure = new Map();
+vi.mock('expo-secure-store', () => ({
+ AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 'after-first-unlock',
+ getItemAsync: async (key: string) => secure.get(key) ?? null,
+ setItemAsync: async (key: string, value: string) => {
+ secure.set(key, value);
+ },
+ deleteItemAsync: async (key: string) => {
+ secure.delete(key);
+ },
+}));
+const { saveHosts, loadSavedHosts } = await import('../src/host/saved-host');
+beforeEach(() => secure.clear());
+const key = noisePublicKey(randomBytes(32));
+const fingerprint = noiseFingerprint(key);
+const invitation: TeamInvitation = {
+ v: 1,
+ host: { id: 'team-host', name: 'Team', fingerprint },
+ routes: ['https://team.example'],
+ username: 'bob',
+ expiresAt: '2030-01-01T00:00:00.000Z',
+};
+const link = (input: unknown) =>
+ `deepseekbot://team?i=${Buffer.from(JSON.stringify(input)).toString('base64url')}`;
+const saved = (hostId = 'team-host', humanId = 'bob-id'): SavedHost => ({
+ hostId,
+ hostName: 'Team',
+ routes: ['https://team.example'],
+ deviceId: `device-${humanId}`,
+ credential: `member.${'a'.repeat(43)}`,
+ member: { humanId, displayName: humanId, username: 'bob', mustChangePassword: true, fingerprint },
+});
+function client(
+ reply: { status: number; body: unknown } = {
+ status: 200,
+ body: {
+ deviceId: 'device-bob-id',
+ credential: `member.${'a'.repeat(43)}`,
+ humanId: 'bob-id',
+ displayName: 'Bob',
+ mustChangePassword: true,
+ host: invitation.host,
+ },
+ },
+) {
+ const request = vi.fn(async (url: string) => {
+ if (url.endsWith('/channel'))
+ return {
+ status: 200,
+ text: async () =>
+ JSON.stringify({
+ host: invitation.host,
+ encryption: { publicKey: Buffer.from(key).toString('hex'), fingerprint },
+ }),
+ };
+ return { status: reply.status, text: async () => JSON.stringify(reply.body) };
+ });
+ const carrier: HostCarrier = {
+ request,
+ randomBytes: () => randomBytes(32),
+ openSocket: () => {
+ throw new Error('unexpected-socket');
+ },
+ };
+ return { carrier, request };
+}
+
+describe('Team invitation parser', () => {
+ it('decodes a Unicode Host identity and normalizes the member entry URL to its origin', () => {
+ const value = {
+ ...invitation,
+ host: { ...invitation.host, name: '团队电脑' },
+ routes: ['https://team.example/botharness-device/team/'],
+ };
+ expect(parseTeamInvitation(link(value), 0)).toEqual({
+ ok: true,
+ value: { ...value, routes: ['https://team.example'] },
+ });
+ });
+ it.each([
+ '',
+ 'https://team.example',
+ 'deepseekbot://team?i=***',
+ 'deepseekbot://pair?i=e30',
+ 'deepseekbot://team?i=e30&i=e30',
+ `deepseekbot://team?i=${'a'.repeat(17_000)}`,
+ ])('rejects malformed input %s', (value) => {
+ expect(parseTeamInvitation(value)).toMatchObject({ ok: false, code: 'invitation-invalid' });
+ });
+ it('distinguishes unsupported versions and expiry, including the exact deadline', () => {
+ expect(parseTeamInvitation(link({ ...invitation, v: 2 }), 0)).toEqual({
+ ok: false,
+ code: 'invitation-version-unsupported',
+ });
+ expect(parseTeamInvitation(link(invitation), Date.parse(invitation.expiresAt))).toEqual({
+ ok: false,
+ code: 'invitation-expired',
+ });
+ });
+ it.each([
+ 'http://192.168.1.2:3080',
+ 'https://localhost',
+ 'https://127.0.0.1',
+ 'https://[::ffff:127.0.0.1]',
+ 'https://user:password@team.example',
+ 'https://team.example?secret=1',
+ ])('refuses unsafe invitation routes %s', (route) => {
+ expect(parseTeamInvitation(link({ ...invitation, routes: [route] }), 0)).toEqual({
+ ok: false,
+ code: 'invitation-invalid',
+ });
+ });
+});
+
+describe('member identity persistence', () => {
+ it('keeps one secure identity per Host and requires confirmation to replace another member', async () => {
+ const bob = saved();
+ const carol = saved('team-host', 'carol-id');
+ const other = saved('other-host');
+ const state = withHost(withHost({ hosts: [] }, bob), other);
+ expect(() => withHost(state, carol)).toThrow('identity-switch-required');
+ expect(prepareMemberIdentity(state, carol)).toEqual({
+ ok: false,
+ code: 'identity-switch-required',
+ });
+ expect(prepareMemberIdentity(state, carol, true)).toEqual({ ok: true, value: carol });
+ await saveHosts(withHost(state, carol, true));
+ expect(await loadSavedHosts()).toEqual({ hosts: [other, carol], current: 'team-host' });
+ expect(secure.get('deepseekbot.hosts.v3')).toContain(carol.credential);
+ expect(memberPasswordGate(carol)).toMatchObject({ kind: 'password-change-required' });
+ expect(
+ memberPasswordGate({ ...carol, member: { ...carol.member!, mustChangePassword: false } }),
+ ).toMatchObject({ kind: 'ready' });
+ expect(memberPasswordGate(undefined)).toEqual({ kind: 'loading' });
+ expect(memberPasswordGate(null)).toEqual({ kind: 'signed-out' });
+ });
+ it('does not ask to replace another Host and permits a confirmed Owner switch with the same pinned Host key', () => {
+ const member = saved();
+ expect(identitySwitchRequired(member, saved('other-host', 'carol-id'))).toBe(false);
+ const { member: _member, ...owner } = member;
+ owner.credential = 'owner-device';
+ const host: SavedHost = {
+ ...owner,
+ encryption: {
+ protocol: 'connect-noise-xk-v1',
+ hostKey: Buffer.from(key).toString('hex'),
+ deviceKey: 'a'.repeat(64),
+ },
+ };
+ expect(() => withHost({ hosts: [member] }, host)).toThrow('identity-switch-required');
+ expect(withHost({ hosts: [member] }, host, true).hosts).toEqual([host]);
+ });
+ it('pins a Host across identity replacement and drops invalid member records on hydration', () => {
+ const bob = saved();
+ const wrong = {
+ ...saved('team-host', 'carol-id'),
+ member: { ...bob.member!, fingerprint: 'b'.repeat(64) },
+ };
+ expect(() => withHost({ hosts: [bob] }, wrong, true)).toThrow('fingerprint-mismatch');
+ expect(parseSavedHosts(JSON.stringify({ hosts: [{ ...bob, member: undefined }] }))).toEqual({
+ hosts: [],
+ });
+ expect(
+ parseSavedHosts(JSON.stringify({ hosts: [bob, { ...bob, deviceId: 'replacement' }] })).hosts,
+ ).toHaveLength(1);
+ });
+});
+
+describe('Team device client', () => {
+ it('verifies identity before sending a password and returns a persistable forced-change identity', async () => {
+ const { carrier, request } = client();
+ const result = await signInTeamDevice({
+ carrier,
+ invitation,
+ password: 'one-time-password',
+ deviceName: 'Phone',
+ now: 0,
+ });
+ expect(result).toMatchObject({
+ ok: true,
+ value: {
+ hostId: 'team-host',
+ member: { humanId: 'bob-id', mustChangePassword: true, fingerprint },
+ },
+ });
+ expect(request.mock.calls.map((call) => call[0])).toEqual([
+ 'https://team.example/botharness-device/channel',
+ 'https://team.example/botharness-device/team/device-sign-in',
+ ]);
+ });
+ it('tries another invited route after network failure and submits the password only on a verified route', async () => {
+ const { carrier, request } = client();
+ const submitted: string[] = [];
+ const raw = carrier.request;
+ carrier.request = async (url, init) => {
+ if (url.startsWith('https://unreachable.ts.net')) throw new TypeError('network');
+ if (url.endsWith('/device-sign-in')) submitted.push(url);
+ return raw(url, init);
+ };
+ const result = await signInTeamDevice({
+ carrier,
+ invitation: { ...invitation, routes: ['https://unreachable.ts.net', ...invitation.routes] },
+ password: 'secret',
+ deviceName: 'Phone',
+ now: 0,
+ });
+ expect(result.ok).toBe(true);
+ expect(submitted).toEqual(['https://team.example/botharness-device/team/device-sign-in']);
+ expect(request).toHaveBeenCalledTimes(2);
+ });
+ it('sends no password when discovery changes Host identity or fingerprint', async () => {
+ const { carrier, request } = client();
+ const result = await signInTeamDevice({
+ carrier,
+ invitation: { ...invitation, host: { ...invitation.host, fingerprint: 'b'.repeat(64) } },
+ password: 'secret',
+ deviceName: 'Phone',
+ now: 0,
+ });
+ expect(result).toEqual({ ok: false, code: 'fingerprint-mismatch' });
+ expect(request).toHaveBeenCalledTimes(1);
+ });
+ it.each([
+ 'credentials-invalid',
+ 'member-suspended',
+ 'team-mode-off',
+ 'insecure-transport',
+ 'fingerprint-mismatch',
+ ] as const)('returns the sign-in refusal %s without copy', async (code) => {
+ const { carrier } = client({
+ status: 403,
+ body: { code, message: 'server copy must not escape' },
+ });
+ expect(
+ await signInTeamDevice({
+ carrier,
+ invitation,
+ password: 'secret',
+ deviceName: 'Phone',
+ now: 0,
+ }),
+ ).toEqual({ ok: false, code });
+ });
+ it('preserves retry time, rejects an altered sign-in identity, and never follows a route outside the invitation', async () => {
+ const limited = client({ status: 429, body: { code: 'rate-limited', retryAfterSeconds: 42 } });
+ expect(
+ await signInTeamDevice({
+ carrier: limited.carrier,
+ invitation,
+ password: 'secret',
+ deviceName: 'Phone',
+ now: 0,
+ }),
+ ).toEqual({ ok: false, code: 'rate-limited', retryAfterSeconds: 42 });
+ const altered = client({
+ status: 200,
+ body: { host: { ...invitation.host, id: 'different-host' } },
+ });
+ expect(
+ await signInTeamDevice({
+ carrier: altered.carrier,
+ invitation,
+ password: 'secret',
+ deviceName: 'Phone',
+ now: 0,
+ }),
+ ).toEqual({ ok: false, code: 'fingerprint-mismatch' });
+ expect(
+ await signInTeamDevice({
+ carrier: limited.carrier,
+ invitation,
+ password: 'secret',
+ deviceName: 'Phone',
+ route: 'https://attacker.example',
+ now: 0,
+ }),
+ ).toEqual({ ok: false, code: 'insecure-transport' });
+ });
+ it('keeps the password gate after a refusal and returns a new ready identity only on success', async () => {
+ const host = saved();
+ const refused = client({ status: 409, body: { code: 'password-reused' } });
+ expect(
+ await changeTeamDevicePassword({
+ carrier: refused.carrier,
+ host,
+ current: 'initial',
+ next: 'reused',
+ }),
+ ).toEqual({ ok: false, code: 'password-reused' });
+ expect(host.member?.mustChangePassword).toBe(true);
+ const accepted = client({ status: 200, body: {} });
+ const result = await changeTeamDevicePassword({
+ carrier: accepted.carrier,
+ host,
+ current: 'initial',
+ next: 'new-password',
+ });
+ expect(result).toMatchObject({ ok: true, value: { member: { mustChangePassword: false } } });
+ });
+ it('gets a typed self-pairing offer through the Host client bridge', async () => {
+ const offer = {
+ link: 'deepseekbot://pair?p=abc',
+ qr: { size: 9, path: 'M0 0h1v1z' },
+ expiresAt: '2030-01-01T00:00:00Z',
+ receipt: 'receipt',
+ };
+ const call = vi.fn(async () => offer);
+ expect(await memberPairingOffer({ call })).toEqual({ ok: true, value: offer });
+ expect(call).toHaveBeenCalledWith('memberPairingOffer');
+ });
+});
diff --git a/changes/4146-team-mode-mobile-sign-in.md b/changes/4146-team-mode-mobile-sign-in.md
new file mode 100644
index 0000000000..e678685d0b
--- /dev/null
+++ b/changes/4146-team-mode-mobile-sign-in.md
@@ -0,0 +1,11 @@
+---
+section: Added
+---
+
+## en
+
+- The iOS and Android app can join a Team mode Host with an invitation link: sign in with the one-time password, choose a new password on the phone, and see which account you use on that Host. A signed-in member can show a one-time code to pair another of their phones without a password ([#4146](https://github.com/BotHarness/DeepSeekBot/issues/4146)).
+
+## zh
+
+- iOS 和 Android App 可以通过邀请链接加入团队模式 Host:用一次性密码登录,在手机上设置新密码,并显示你在该 Host 上使用的账号。已登录的成员可以出示一次性配对码,让自己的另一台手机免密码登录([#4146](https://github.com/BotHarness/DeepSeekBot/issues/4146))。
diff --git a/docs/bot-cli.md b/docs/bot-cli.md
index c55de0409c..34a0998ab1 100644
--- a/docs/bot-cli.md
+++ b/docs/bot-cli.md
@@ -2055,6 +2055,8 @@ deepseekbot team-mode owner-password --password-stdin < owner-password.txt
deepseekbot team-mode on
deepseekbot members create --username bob --display-name Bob --initial-password-file ./bob-initial.txt
deepseekbot members list
+deepseekbot members invite bob
+deepseekbot --as bob members pairing-offer
deepseekbot members reset-password bob --initial-password-file ./bob-reset.txt
deepseekbot channels set-public on
deepseekbot --as bob members password --password-stdin < password-change.json
@@ -2112,3 +2114,7 @@ deepseekbot models allowed [--as ]
```
Tool effect declarations (E1) preserve the existing tool commands and approval outcomes. Full Access, saved rules, Secrets, device targets and Workspace Grants retain their existing checks; no new route or CLI authority is introduced.
+
+`members invite ` resolves the username with `members.manage` and the target-role ceiling and returns `{ link, qr: { size, path }, expiresAt }`. The invitation contains the Host identity fingerprint, reachable HTTPS / encrypted-gateway routes and username; it contains no initial password. Deliver that password separately. `--as members pairing-offer` creates a ten-minute, single-use pairing offer for that member alone, with an additional `receipt`. It refuses until the initial password has changed. Redemption creates a `paired-device` member grant for the same Human, without creating an Owner device or obtaining an Owner cookie.
+
+The phone stores one secure identity per Host ID. Replacing a different member on the same Host requires confirmation and clears the previous identity's local content. The phone verifies the invitation fingerprint before sign-in; the Host also refuses `fingerprint-mismatch`. Every other device API and mux refuses `password-change-required` until the initial password changes. Password routes retain `credentials-invalid`, `password-weak`, `password-reused` and `rate-limited` with `retryAfterSeconds`; device passwords cannot use the browser's insecure HTTP exception. iOS and Android native acceptance are recorded separately.
diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md
index 5416e034d7..7b192b7b31 100644
--- a/docs/bot-cli.zh.md
+++ b/docs/bot-cli.zh.md
@@ -1975,6 +1975,8 @@ deepseekbot team-mode owner-password --password-stdin < owner-password.txt
deepseekbot team-mode on
deepseekbot members create --username bob --display-name Bob --initial-password-file ./bob-initial.txt
deepseekbot members list
+deepseekbot members invite bob
+deepseekbot --as bob members pairing-offer
deepseekbot members reset-password bob --initial-password-file ./bob-reset.txt
deepseekbot channels set-public on
deepseekbot --as bob members password --password-stdin < password-change.json
@@ -2053,3 +2055,7 @@ Web 手动检查请求最多等待 25 秒,关闭自检卡片会取消请求。
公网阶段仅对 DNS、网络、超时及 HTTP 429/5xx 短暂失败重试:最多四次,间隔 1/3/6 秒,仍受同一个 20 秒总时限约束。证书或身份失败不重试。每次自检完成后,界面刷新一次账号电脑列表。
工具效果声明(E1)保持既有工具命令与审批结果。Full Access、保存规则、Secrets、设备目标和 Workspace Grant 仍使用原检查;不新增 route 或 CLI 权限。
+
+`members invite ` 需要 `members.manage` 并遵循目标角色权限上限,将用户名解析为 Human ID,返回 `{ link, qr: { size, path }, expiresAt }`。邀请内容含 Host 身份指纹、可达的 HTTPS / 加密网关路由和用户名,不含初始密码;初始密码须通过另一路径提供。`--as members pairing-offer` 只为该成员自己创建十分钟内有效、只能使用一次的配对码,并额外返回 `receipt`;首次改密完成前拒绝。兑换后创建同一 Human 的 `paired-device` 成员授权,不会创建 Owner 设备或获取 Owner cookie。
+
+手机以 Host ID 保存一个安全存储身份,切换同一 Host 的成员须确认并清除旧身份的本地内容。手机登录前验证邀请指纹;Host 也拒绝 `fingerprint-mismatch`。首次改密前,其他设备 API 和 mux 均拒绝 `password-change-required`。密码接口保留 `credentials-invalid`、`password-weak`、`password-reused` 和带 `retryAfterSeconds` 的 `rate-limited`;设备密码不能使用浏览器的明文 HTTP 例外。iOS 和 Android 原生验收分别记录。
diff --git a/packages/core/src/bots/cli-team.ts b/packages/core/src/bots/cli-team.ts
index 1a458bb0c3..01e89c0822 100644
--- a/packages/core/src/bots/cli-team.ts
+++ b/packages/core/src/bots/cli-team.ts
@@ -65,7 +65,7 @@ export const TEAM_COMMANDS = [
{
command: 'members',
description:
- 'list | create --username --display-name --initial-password-file [--role-ids] | roles --set | reset-password --initial-password-file | deactivate|reactivate | transfer --to [--preview] | purge --preview | purge --token-stdin --confirm | change-password --password-stdin [--sign-out-others=true|false]',
+ 'list | invite | pairing-offer | create --username --display-name --initial-password-file [--role-ids] | roles --set | reset-password --initial-password-file | deactivate|reactivate | transfer --to [--preview] | purge --preview | purge --token-stdin --confirm | change-password --password-stdin [--sign-out-others=true|false]',
},
] as const;
@@ -336,6 +336,15 @@ export async function runTeamCommand(
roleIds: ids(values.set),
});
if (action === 'list' && rest.length === 1) return rpc('members', {});
+ if (action === 'pairing-offer' && rest.length === 1) return rpc('memberPairingOffer', {});
+ if (action === 'invite' && argument && rest.length === 2) {
+ const members = z
+ .array(z.object({ username: z.string(), humanId: z.string() }))
+ .parse(await rpc('members', {}));
+ const member = members.find((entry) => entry.username === argument);
+ if (!member) throw new CliLiveError('member-not-found', 'member-not-found');
+ return rpc('memberInvitation', { humanId: member.humanId });
+ }
if (
(action === 'password' || action === 'change-password') &&
rest.length === 1 &&
diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts
index 70225463da..7e53f51803 100644
--- a/packages/core/src/bridge/rpc.ts
+++ b/packages/core/src/bridge/rpc.ts
@@ -522,6 +522,12 @@ export class BotharnessBridgeService extends TypertRemoteService {
);
return unwrapAsync(this.methods.memberPasswordChange({ current, next, signOutOthers }));
}
+ memberInvitation(humanId: string) {
+ return unwrapAsync(this.methods.memberInvitation({ humanId }));
+ }
+ memberPairingOffer() {
+ return unwrapAsync(this.methods.memberPairingOffer({}));
+ }
memberPasswordReset(humanId: string) {
return unwrapAsync(this.methods.memberPasswordReset({ humanId }));
}
@@ -3180,6 +3186,8 @@ markRemoteMethods(BotharnessBridgeService.prototype, [
'ownerTransfer',
'memberPasswordChange',
'memberPasswordReset',
+ 'memberInvitation',
+ 'memberPairingOffer',
'channelRoleDirectory',
'browsableChannels',
'channelJoin',
diff --git a/packages/core/src/database/schema-plan.ts b/packages/core/src/database/schema-plan.ts
index 01f49b0867..266af24ebb 100644
--- a/packages/core/src/database/schema-plan.ts
+++ b/packages/core/src/database/schema-plan.ts
@@ -3671,6 +3671,20 @@ const MIGRATION_LEDGER_MIGRATION: SchemaMigration = {
migrate() {},
};
+const MEMBER_DEVICES_MIGRATION: SchemaMigration = {
+ id: 'member-devices',
+ module: 'team',
+ description: 'Member grants distinguish browser sessions and paired devices',
+ migrate(database) {
+ database.exec(`
+ ALTER TABLE member_grants ADD COLUMN kind TEXT NOT NULL DEFAULT 'browser-session'
+ CHECK (kind IN ('browser-session', 'paired-device'));
+ ALTER TABLE member_grants ADD COLUMN device_name TEXT;
+ ALTER TABLE member_grants ADD COLUMN public_key TEXT;
+ `);
+ },
+};
+
export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([
SESSION_OWNERSHIP_MIGRATION,
MESSAGING_TRACER_MIGRATION,
@@ -3825,4 +3839,5 @@ export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([
PRIVATE_CONTENT_AUDIT_MIGRATION,
MINIMAL_MEMBER_MIGRATION,
MIGRATION_LEDGER_MIGRATION,
+ MEMBER_DEVICES_MIGRATION,
]);
diff --git a/packages/core/src/devices/encrypted-gateway.ts b/packages/core/src/devices/encrypted-gateway.ts
index 9ccac7f9ed..9ddd19c13d 100644
--- a/packages/core/src/devices/encrypted-gateway.ts
+++ b/packages/core/src/devices/encrypted-gateway.ts
@@ -1,3 +1,5 @@
+import type { MemberDevices } from '../team/devices.js';
+import { TeamError } from '../team/error.js';
import type { OfferVerification } from './connect-account.js';
import type { IncomingMessage } from 'node:http';
import { request } from 'node:http';
@@ -62,6 +64,7 @@ function pathAllowed(path: string): boolean {
].includes(name) ||
name === '/botharness-device/push' ||
name.startsWith('/botharness-device/push/') ||
+ name === '/botharness-device/team/device-password' ||
name === '/botharness-device/feed-read' ||
name === '/botharness-device/unpair' ||
name === '/botharness-device/devices/remove'
@@ -99,6 +102,7 @@ let nextCallChannel = 0;
export function createEncryptedGateway(options: {
pairing: DevicePairing;
+ memberDevices?: MemberDevices;
route?: 'connect' | 'lan';
key(): Promise;
port(): number;
@@ -136,7 +140,7 @@ export function createEncryptedGateway(options: {
encrypted = 0,
upgrading = 0;
const changed = () => options.changed?.({ negotiating, encrypted });
- const serve = (socket: WebSocket, key: Uint8Array) => {
+ const serve = (socket: WebSocket, key: Uint8Array, remoteAddress: string) => {
const channel = new ConnectChannel({
role: 'responder',
hostId: options.pairing.host().id,
@@ -571,6 +575,11 @@ export function createEncryptedGateway(options: {
(method !== 'GET' && method !== 'POST')
)
throw new Error('channel-request-invalid');
+ if (
+ credential?.startsWith('member.') &&
+ /\/(?:computer|browser|voice|direct)(?:\/|$)/u.test(path)
+ )
+ throw new Error('remote-access/denied');
if (path === `/botharness-device${LOCAL_VIDEO_PATH}`) return video(id, input);
if (path === `/botharness-device${VOICE_CALL_PATH}`) return call(id, input);
if (path === `/botharness-device${DIRECT_PATH}`) return direct(id, input);
@@ -633,6 +642,29 @@ export function createEncryptedGateway(options: {
const type = input['type'];
if (!admitted) {
const publicKey = Buffer.from(channel.peerKey()).toString('hex');
+ if (type === 'team-sign-in' && options.memberDevices) {
+ try {
+ const result = await options.memberDevices.signIn(
+ input['input'],
+ remoteAddress,
+ publicKey,
+ );
+ if (!closed) send({ type: 'team-signed-in', result: { ok: true, value: result } });
+ } catch (error) {
+ if (!closed)
+ send({
+ type: 'team-signed-in',
+ result: {
+ ok: false,
+ code: error instanceof TeamError ? error.code : 'invalid-input',
+ ...(error instanceof TeamError && error.retryAfterSeconds
+ ? { retryAfterSeconds: error.retryAfterSeconds }
+ : {}),
+ },
+ });
+ }
+ return;
+ }
if (type === 'relationship') {
if (!options.relationship) return refuse('relationship-unavailable');
const result = await options.relationship(publicKey, input['command']);
@@ -691,6 +723,13 @@ export function createEncryptedGateway(options: {
host: paired.host,
deviceId: paired.device.id,
credential: paired.credential,
+ ...(paired.humanId === undefined
+ ? {}
+ : {
+ humanId: paired.humanId,
+ displayName: paired.displayName,
+ mustChangePassword: paired.mustChangePassword,
+ }),
});
return;
}
@@ -840,7 +879,9 @@ export function createEncryptedGateway(options: {
return;
}
const identity = key;
- server.handleUpgrade(request, socket, head, (client) => serve(client, identity));
+ server.handleUpgrade(request, socket, head, (client) =>
+ serve(client, identity, request.socket.remoteAddress ?? 'unknown'),
+ );
} catch {
socket.destroy();
} finally {
diff --git a/packages/core/src/devices/gateway.ts b/packages/core/src/devices/gateway.ts
index e944567bab..2488b25ac1 100644
--- a/packages/core/src/devices/gateway.ts
+++ b/packages/core/src/devices/gateway.ts
@@ -1,3 +1,4 @@
+import { memberDeviceRequest, deviceFailure } from '../team/device-http.js';
import { TEAM_PATH, type TeamHttp } from '../team/http.js';
import { createHash, randomBytes } from 'node:crypto';
import { request as httpRequest, type IncomingMessage, type ServerResponse } from 'node:http';
@@ -268,11 +269,16 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa
input = JSON.parse(text ?? '') as typeof input;
} catch {}
if (typeof input.offer !== 'string') return refuse(response, 401, 'offer-invalid');
- const result = pairing.redeem({
- offer: input.offer,
- ...(typeof input.name === 'string' ? { name: input.name } : {}),
- ...(typeof input.verifier === 'string' ? { verifier: input.verifier } : {}),
- });
+ let result;
+ try {
+ result = pairing.redeem({
+ offer: input.offer,
+ ...(typeof input.name === 'string' ? { name: input.name } : {}),
+ ...(typeof input.verifier === 'string' ? { verifier: input.verifier } : {}),
+ });
+ } catch (error) {
+ return deviceFailure(response, error);
+ }
if (!result.ok) return refuse(response, 401, result.code);
response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
response.end(
@@ -280,6 +286,13 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa
deviceId: result.device.id,
credential: result.credential,
host: result.host,
+ ...(result.humanId === undefined
+ ? {}
+ : {
+ humanId: result.humanId,
+ displayName: result.displayName,
+ mustChangePassword: result.mustChangePassword,
+ }),
}),
);
};
@@ -651,6 +664,10 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa
return {
async handle(request, response) {
const path = new URL(request.url ?? '/', 'http://device').pathname;
+ if (memberDeviceRequest(request) && path !== `${TEAM_PATH}/device-sign-in`) {
+ if (options.team?.device) return options.team.device.handle(request, response);
+ return refuse(response, 401, 'device-unknown');
+ }
if (path === TEAM_PATH || path.startsWith(`${TEAM_PATH}/`)) {
if (options.team) return options.team.handle(request, response);
return refuse(response, 404, 'not-found');
@@ -717,6 +734,10 @@ export function createDeviceGateway(options: DeviceGatewayOptions): DeviceGatewa
async upgrade(request, socket, head) {
const pathname = new URL(request.url ?? '/', 'http://device').pathname;
+ if (memberDeviceRequest(request)) {
+ if (options.team?.device) return options.team.device.upgrade(request, socket, head);
+ return refuseUpgrade(socket, 401, 'device-unknown');
+ }
if (
pathname !== DEVICE_MUX_PATH &&
!(DEVICE_SIGNALING_PATHS as readonly string[]).includes(pathname)
diff --git a/packages/core/src/devices/http.ts b/packages/core/src/devices/http.ts
index e0416ca601..3fb0684222 100644
--- a/packages/core/src/devices/http.ts
+++ b/packages/core/src/devices/http.ts
@@ -33,6 +33,7 @@ const headers = {
};
export interface PairingPayload {
+ member?: true;
v: 1 | 2;
encryption?: EncryptionIdentity & {
loopback?: 'encrypted';
@@ -76,7 +77,7 @@ export function pairingLink(payload: PairingPayload): string {
return `${PAIRING_LINK_SCHEME}://pair?p=${encoded}`;
}
-function qrPath(text: string): { size: number; path: string } {
+export function qrPath(text: string): { size: number; path: string } {
const { size, data } = encode(text, { ecc: 'M', border: 0 });
let path = '';
data.forEach((row, y) => {
diff --git a/packages/core/src/devices/mount.ts b/packages/core/src/devices/mount.ts
index d68052a8a7..c68914d67a 100644
--- a/packages/core/src/devices/mount.ts
+++ b/packages/core/src/devices/mount.ts
@@ -1,3 +1,4 @@
+import { createMemberDevices } from '../team/devices.js';
import { createConnectHealth } from './connect-health.js';
import { pairedDeviceHuman, deviceOwnsRequest } from '../team/device-audience.js';
import { mountTeamGateway } from '../team/mount.js';
@@ -92,6 +93,7 @@ interface ConnectionLike {
interface WebServerLike {
readonly port: number;
+ getOrigin?(): string;
register(route: {
kind: 'exact' | 'prefix';
path: string;
@@ -183,6 +185,23 @@ export function mountDevicePairing(
const pairing = createDevicePairing({
database: attachOperationalModule(options.database, 'device-pairing'),
hostName: hostname().replace(/\.local$/u, ''),
+ ...(options.team
+ ? {
+ members: {
+ redeem: (humanId: string, name: string, publicKey?: string) =>
+ options.team!.createDeviceGrant(humanId, name, publicKey),
+ admit: (authorization: string | undefined, publicKey?: string) => {
+ const peer = options.team!.admitDevice(authorization, publicKey);
+ return peer?.principal.kind === 'botharness-member'
+ ? options.team!.device(peer.principal.grantId)
+ : undefined;
+ },
+ check: (deviceId: string) => options.team!.device(deviceId),
+ attach: (deviceId: string, close: () => void) =>
+ options.team!.attachDeviceStream(deviceId, close),
+ },
+ }
+ : {}),
...(options.team ? { ownerHumanId: () => options.team!.ownerContext().humanId } : {}),
record: (event) => write('device-pairing', event.phase, `device-pairing ${detail(event)}`),
onRevoked: (deviceId) => {
@@ -221,6 +240,17 @@ export function mountDevicePairing(
);
const identity = createNoiseIdentity(options.credentials ?? (() => undefined));
ctx.effect(() => () => identity.close(), 'botharness: Host encryption identity');
+ let memberRoutes: () => Promise = async () => [];
+ const memberDevices = options.team
+ ? createMemberDevices({
+ team: options.team,
+ pairing,
+ encryption: identity.publicIdentity,
+ routes: () => memberRoutes(),
+ })
+ : undefined;
+ if (options.team && memberDevices)
+ ctx.effect(() => options.team!.bindDevices(memberDevices), 'botharness: member invitations');
const botNetworks = createBotNetworkRoutes({
withdrawn: async (hostId) => options.botNetwork?.withdrawNetworkMembership(hostId),
});
@@ -459,6 +489,7 @@ export function mountDevicePairing(
gateway: () =>
createEncryptedGateway({
pairing,
+ ...(memberDevices ? { memberDevices } : {}),
relationship: relationshipControl.receive,
key: identity.key,
port: () => webServer.port,
@@ -602,6 +633,7 @@ export function mountDevicePairing(
webCtx.effect(() => () => directPeers.close(), 'botharness: direct device peers');
const encrypted = createEncryptedGateway({
pairing,
+ ...(memberDevices ? { memberDevices } : {}),
relationship: relationshipControl.receive,
key: identity.key,
port: () => webServer.port,
@@ -888,6 +920,12 @@ export function mountDevicePairing(
const others = status.routes.filter((route) => route.kind !== 'loopback');
return { ...status, routes: [...others, tunnel, ...loopback] };
};
+ memberRoutes = async () => [
+ ...(webServer.getOrigin ? [webServer.getOrigin()] : []),
+ ...(await routes()).routes
+ .filter((route) => route.ready && route.kind !== 'private')
+ .map((route) => route.url),
+ ];
webCtx.effect(
() =>
connection.fetch.register({
@@ -971,6 +1009,7 @@ export function mountDevicePairing(
teamCtx,
teamService,
() => pairing.host().name,
+ memberDevices!,
(phase, facts) =>
write(
'team',
@@ -995,6 +1034,9 @@ export function mountDevicePairing(
});
const team = teamService
? {
+ get device() {
+ return memberGateway?.device;
+ },
async handle(request: IncomingMessage, response: ServerResponse) {
if (memberGateway) return memberGateway.handle(request, response);
response.writeHead(503, {
diff --git a/packages/core/src/devices/pairing.ts b/packages/core/src/devices/pairing.ts
index a260cee767..e5e7104269 100644
--- a/packages/core/src/devices/pairing.ts
+++ b/packages/core/src/devices/pairing.ts
@@ -17,6 +17,7 @@ export interface HostIdentity {
export interface PairedDevice {
id: string;
name: string;
+ humanId?: string;
publicKey?: string;
pairedAt: string;
lastSeenAt?: string;
@@ -51,7 +52,15 @@ export type OfferRefusal =
export type DeviceRefusal = 'device-credential-missing' | 'device-unknown' | 'device-revoked';
export type Redemption =
- | { ok: true; device: PairedDevice; credential: string; host: HostIdentity }
+ | {
+ ok: true;
+ device: PairedDevice;
+ credential: string;
+ host: HostIdentity;
+ humanId?: string;
+ displayName?: string;
+ mustChangePassword?: boolean;
+ }
| { ok: false; code: OfferRefusal };
export type Admission = { ok: true; device: PairedDevice } | { ok: false; code: DeviceRefusal };
@@ -76,6 +85,7 @@ export interface DevicePairing {
createOffer(binding?: {
verifierHash?: string;
name?: string;
+ humanId?: string;
relationshipId?: string;
}): PairingOffer;
offerStatus(receipt: string): OfferStatus;
@@ -114,6 +124,22 @@ export interface DevicePairingOptions {
record?: (event: DevicePairingEvent) => void;
onRevoked?: (deviceId: string) => void;
onPaired?: (device: PairedDevice) => void;
+ members?: {
+ redeem(
+ humanId: string,
+ name: string,
+ publicKey?: string,
+ ): {
+ deviceId: string;
+ credential: string;
+ humanId: string;
+ displayName: string;
+ mustChangePassword: boolean;
+ };
+ admit(authorization: string | undefined, publicKey?: string): PairedDevice | undefined;
+ check(deviceId: string): PairedDevice | undefined;
+ attach(deviceId: string, close: () => void): () => void;
+ };
}
interface Row {
@@ -166,6 +192,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
expiresAt: number;
humanId: string;
receipt: string;
+ memberHumanId?: string;
verifierHash?: string;
name?: string;
publicKey?: string;
@@ -283,8 +310,9 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
offers.set(digest(offer).toString('hex'), {
expiresAt,
receipt,
- humanId: ownerHumanId(),
...binding,
+ humanId: ownerHumanId(),
+ ...(binding?.humanId === undefined ? {} : { memberHumanId: binding.humanId }),
});
record({ phase: 'offer-created' });
return { offer, expiresAt: iso(expiresAt), receipt };
@@ -324,6 +352,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
if (
!open ||
open.humanId !== ownerHumanId() ||
+ open.memberHumanId !== undefined ||
open.publicKey !== undefined ||
open.verifierHash !== undefined
)
@@ -348,7 +377,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
if (open.publicKey === undefined) {
open.publicKey = input.publicKey;
open.name = deviceName(input.name ?? open.name);
- open.approved = false;
+ open.approved = open.memberHumanId !== undefined;
}
return { ok: true, receipt: open.receipt };
},
@@ -393,6 +422,10 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
},
admitKey(authorization, publicKey) {
+ if (authorization?.startsWith('Device member.')) {
+ const member = options.members?.admit(authorization, publicKey);
+ return member ? { ok: true, device: member } : { ok: false, code: 'device-unknown' };
+ }
const admitted = this.admit(authorization);
if (!admitted.ok) return admitted;
if (admitted.device.publicKey !== publicKey) return { ok: false, code: 'device-unknown' };
@@ -425,6 +458,30 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
record({ phase: 'offer-expired' });
return { ok: false, code: 'offer-expired' };
}
+ if (open.memberHumanId !== undefined) {
+ const result = options.members?.redeem(
+ open.memberHumanId,
+ deviceName(input.name ?? open.name),
+ input.publicKey,
+ );
+ if (!result) {
+ settle(open.receipt, { state: 'refused' });
+ return { ok: false, code: 'offer-invalid' };
+ }
+ settle(open.receipt, { state: 'redeemed', deviceId: result.deviceId });
+ record({ phase: 'offer-redeemed', deviceId: result.deviceId });
+ return {
+ ok: true,
+ ...result,
+ device: {
+ id: result.deviceId,
+ humanId: result.humanId,
+ name: deviceName(input.name ?? open.name),
+ pairedAt: iso(now()),
+ },
+ host: host(),
+ };
+ }
const id = token(16);
const secret = token(32);
const pairedAt = iso(now());
@@ -500,6 +557,10 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
},
admit(authorization) {
+ if (authorization?.startsWith('Device member.')) {
+ const member = options.members?.admit(authorization);
+ return member ? { ok: true, device: member } : { ok: false, code: 'device-unknown' };
+ }
const match = CREDENTIAL.exec(authorization?.trim() ?? '');
if (match === null) {
record({ phase: 'device-refused', code: 'device-credential-missing' });
@@ -519,6 +580,8 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
},
check(deviceId) {
+ const member = options.members?.check(deviceId);
+ if (member) return { ok: true, device: member };
const current = row(deviceId);
if (current === undefined) {
record({ phase: 'device-refused', code: 'device-unknown', deviceId });
@@ -581,6 +644,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin
return open.length;
},
attachStream(deviceId, close) {
+ if (options.members?.check(deviceId)) return options.members.attach(deviceId, close);
const open = streams.get(deviceId) ?? new Set();
open.add(close);
streams.set(deviceId, open);
diff --git a/packages/core/src/team/M8.md b/packages/core/src/team/M8.md
new file mode 100644
index 0000000000..9ddf568ab5
--- /dev/null
+++ b/packages/core/src/team/M8.md
@@ -0,0 +1,33 @@
+# M8 device carrier and mobile integration
+
+Issue #4146 adds application-defined Consumers of the existing Team service and DSH API Gateway. SQLite `member_grants` remains the durable authority. The named `member-devices` migration, appended after `migration-ledger`, adds `kind` (`browser-session` or `paired-device`), `device_name` and the optional Noise `public_key`. Device IDs are grant IDs, and the credential is `member.`; only its SHA-256 digest is stored. M3 device management lists those grants as named paired devices and revokes them through the Team service. The append-only ledger assigns its generation from its final list position; the frozen main prefix is unchanged.
+
+The Device Gateway recognizes the member credential before its Owner proxy. Unary calls invoke the Gateway with that grant's member Peer; mux opens use `wireStream.open` with the same Peer and remote-access policy. No member operation calls the Owner cookie mint/proxy. Suspension, reset, mode off and revocation retain M1's grant and Peer invalidation. Password changes preserve the caller's grant while retiring other initial-password grants. Native DSH business methods remain denied. Owner-paired devices retain their original path.
+
+Invitations require `members.manage` and the existing target-role ceiling. They carry identity, username, expiry and HTTPS addresses only. Passwords travel separately. Public Connect addresses use pinned Noise; ordinary Host HTTPS uses certificate-validated requests after fingerprint discovery. A private relay that additionally requires an admission token is excluded from invitations because an invitation cannot contain that token. Encrypted LAN invitation discovery is not introduced here. Member self-pairing uses the existing ten-minute, single-use offer lifecycle; redeeming its QR creates a device grant for the offer's Human. The offer itself authorizes the redeeming Noise key and does not require an Owner approval.
+
+## Mobile screen contract
+
+All functions below live under `apps/mobile/src/host/`. They return codes, without UI copy.
+
+- `team-invitation.ts`: `parseTeamInvitation(link, now?) -> TeamResult`. `TeamInvitation` is `{ v: 1, host: { id, name, fingerprint }, routes, username, expiresAt }`. Parsing normalizes member-entry URLs to origins and strips unrecognized fields.
+- `team-client.ts`: `signInTeamDevice({ carrier, invitation, password, deviceName, route?, signal?, now? }) -> Promise>`. It discovers and checks the Host identity before sending a password. `route`, when provided, must be in the parsed invitation. Without it, unreachable routes fall through to the next invited route within a shared thirty-second deadline; a credential or fingerprint refusal never retries another Host. It creates a phone Noise key and returns a secure-store-ready identity. Obtain the carrier with `nativeCarrier()`; screens do not call fetch.
+- `team-client.ts`: `changeTeamDevicePassword({ carrier, host, current, next, signal? }) -> Promise>`. The input Host remains gated on failure. Success returns a new Host with `member.mustChangePassword: false`; persist it through `hostSession.pairMember` before entering the normal Client.
+- A received member self-pairing QR can use the existing `parsePairingLink` and `redeemPairing` functions in `pairing.ts` to obtain its pending `SavedHost`, then `hostSession.pairMember` for confirmation and persistence. Its `member: true` payload forces a new member grant instead of treating a scan as an existing pairing route update.
+- `team-client.ts`: `memberPairingOffer(client) -> Promise>`, where `MemberPairingOffer` is `{ link, qr: { size, path }, expiresAt, receipt }`. The Host derives the caller's Human; no target Human is accepted.
+- `member-identity.ts`: `prepareMemberIdentity(savedHosts, host, confirmed?)` returns either the prepared Host or `identity-switch-required` / `fingerprint-mismatch`. `identitySwitchRequired(previous, next)` compares Human IDs for the same stored Host.
+- `host-session.ts`: `hostSession.pairMember(host, { confirmedIdentitySwitch? }) -> Promise>`. Call once to persist a sign-in or password-change result. On `identity-switch-required`, retain the pending Host in memory, ask for confirmation, and retry with `confirmedIdentitySwitch: true`. Cancel by discarding that pending result. Confirmation never bypasses fingerprint pinning. The serialized mutation clears the previous identity's conversations, drafts, media and presentation state before replacement. Password-gated Hosts remain stored, but their normal Host Clients are not started.
+- `member-identity.ts`: `memberPasswordGate(savedHost)` returns `{ kind: 'loading' }` before hydration, `{ kind: 'signed-out' }`, `{ kind: 'owner' }`, or `{ kind: 'password-change-required' | 'ready', host, member }`. Wait for Host-session hydration before choosing a screen.
+- `SavedHost.member?: HostMemberIdentity` is `{ humanId, displayName, username, fingerprint, mustChangePassword }`. Self-pairing can have an empty username; use `displayName` for the Host row. The existing SecureStore document remains keyed by `hostId`, preserves several Hosts and restores one identity per Host. `loadSavedHosts` / `saveHosts` remain the storage adapters; screens use the Host session so runtime state follows persistence.
+
+`TeamResult` is `{ ok: true, value: T } | { ok: false, code: TeamErrorCode, retryAfterSeconds?: number }`.
+
+`InvitationError`: `invitation-invalid`, `invitation-expired`, `invitation-version-unsupported`.
+
+`TeamErrorCode` additionally includes `credentials-invalid`, `rate-limited`, `insecure-transport`, `team-mode-off`, `member-suspended`, `fingerprint-mismatch`, `password-change-required`, `password-weak`, `password-reused`, `invalid-input`, `unreachable`, `response-invalid`, `request-cancelled`, `identity-switch-required`, `storage-failed`, `remote-access/denied`. Screens own all translations, labels and confirmation copy. No native package or configuration changes are required.
+
+## Performance and verification boundary
+
+Password hashing retains M1's two workers, sixteen waiting operations and username/socket rate limits. Grant admission uses indexed lookups and throttles last-seen writes to once per minute; the regression repeats admission without new writes. The member mux permits 64 sockets, 16 logical streams per socket and 256 logical streams per Host, with 1 MiB incoming frames and 4 MiB outgoing backpressure. Peer disposal and Plugin unload close sockets and cancel streams. No polling timer or dependency was added to the mobile idle path.
+
+A task-local real Host check compared one existing browser sign-in with one Noise device sign-in, then changed the initial password and confirmed a native business API refusal. Its timings are latency observations under local load, not a speedup claim. The Node integration also covers member-owned and forbidden Channel unary/stream dispatch, every sign-in refusal, forced-password failures, grant revocation, and self-pairing single use/expiry. Native iOS, Android and Human acceptance remain separate from Host and module verification. Claude owns the screens, visible copy, bilingual release fragment and device QA.
diff --git a/packages/core/src/team/bridge.ts b/packages/core/src/team/bridge.ts
index a0eb42a42d..e5af94f4a8 100644
--- a/packages/core/src/team/bridge.ts
+++ b/packages/core/src/team/bridge.ts
@@ -172,6 +172,11 @@ export function createTeamBridge(human: HumanContext, team: TeamService | undefi
.parse(payload);
return service.createMember(human, username, displayName, roleIds);
}),
+ memberInvitation: (payload: unknown) =>
+ call((service) =>
+ service.invitation(human, z.object({ humanId: z.string().min(1) }).parse(payload).humanId),
+ ),
+ memberPairingOffer: (_payload: unknown) => call((service) => service.pairingOffer(human)),
memberPasswordReset: (payload: unknown) =>
call((service) =>
service.resetPassword(
diff --git a/packages/core/src/team/device-http.ts b/packages/core/src/team/device-http.ts
new file mode 100644
index 0000000000..e2aee44f00
--- /dev/null
+++ b/packages/core/src/team/device-http.ts
@@ -0,0 +1,282 @@
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import type { Duplex } from 'node:stream';
+import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol';
+import type { TypertGateway } from '@deepseek-ai/dsh-api-gateway';
+import { WebSocket, WebSocketServer } from 'ws';
+import { z } from 'zod';
+import { TeamError, type TeamService } from './service.js';
+import type { MemberDevices } from './devices.js';
+import { passwordTransportAllowed, readTeamBody, teamJson } from './http.js';
+
+const PREFIX = '/botharness-device';
+const SIGN_IN = `${PREFIX}/team/device-sign-in`;
+const PASSWORD = `${PREFIX}/team/device-password`;
+const rpcSchema = z.object({
+ type: z.literal('client-request'),
+ rpcId: z.string().max(256),
+ method: z.string(),
+ payload: z.object({ args: z.record(z.string(), z.unknown()).optional() }).optional(),
+});
+const frameSchema = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('open'),
+ streamId: z.string().min(1).max(256),
+ endpoint: z.string(),
+ payload: z.unknown(),
+ }),
+ z.object({ type: z.literal('cancel'), streamId: z.string().min(1).max(256) }),
+]);
+function authorization(request: IncomingMessage): string | undefined {
+ const value = request.headers.authorization;
+ return Array.isArray(value) ? value[0] : value;
+}
+export function memberDeviceRequest(request: IncomingMessage): boolean {
+ return authorization(request)?.startsWith('Device member.') === true;
+}
+function failure(error: unknown, gateway: TypertGateway) {
+ return error instanceof TeamError
+ ? { code: error.code, message: error.code, details: {} }
+ : error instanceof z.ZodError
+ ? { code: 'invalid-input', message: 'invalid-input', details: {} }
+ : gateway.wireStream.failure(error);
+}
+export function deviceFailure(response: ServerResponse, error: unknown): void {
+ const code =
+ error instanceof TeamError
+ ? error.code
+ : error instanceof z.ZodError
+ ? 'invalid-input'
+ : 'internal';
+ teamJson(
+ response,
+ code === 'credentials-invalid'
+ ? 401
+ : code === 'rate-limited'
+ ? 429
+ : code === 'password-reused'
+ ? 409
+ : ['invalid-input', 'password-weak'].includes(code)
+ ? 400
+ : code === 'internal'
+ ? 503
+ : 403,
+ {
+ code,
+ ...(error instanceof TeamError && error.retryAfterSeconds
+ ? { retryAfterSeconds: error.retryAfterSeconds }
+ : {}),
+ },
+ );
+}
+
+export function createTeamDeviceHttp(options: {
+ team: TeamService;
+ devices: MemberDevices;
+ gateway: TypertGateway;
+ tls(): boolean;
+}) {
+ const sockets = new Set<() => void>();
+ let activeStreams = 0;
+ const peerFor = (request: IncomingMessage) => {
+ const peer = options.team.admitDevice(authorization(request));
+ if (!peer) throw new TeamError('credentials-invalid');
+ return peer;
+ };
+ const assertDevice = (peer: PeerScope) => options.team.assertCall(peer.principal, 'device');
+ const transport = (request: IncomingMessage) => {
+ if (!options.tls() && !passwordTransportAllowed(request, options, false))
+ throw new TeamError('insecure-transport');
+ };
+ return {
+ async handle(request: IncomingMessage, response: ServerResponse): Promise {
+ const path = new URL(request.url ?? '/', 'http://device').pathname;
+ try {
+ if (request.headers.origin || request.headers['sec-fetch-site'] === 'cross-site')
+ throw new TeamError('origin-refused');
+ if (path === SIGN_IN && request.method === 'POST') {
+ transport(request);
+ return teamJson(
+ response,
+ 200,
+ await options.devices.signIn(
+ await readTeamBody(request),
+ request.socket.remoteAddress ?? 'unknown',
+ ),
+ );
+ }
+ const peer = peerFor(request);
+ if (path === PASSWORD && request.method === 'POST') {
+ transport(request);
+ const input = z
+ .object({ current: z.string().max(1024), next: z.string().max(1024) })
+ .parse(await readTeamBody(request));
+ await options.team.changeWebPassword(
+ peer.principal,
+ input.current,
+ input.next,
+ request.socket.remoteAddress ?? 'unknown',
+ );
+ return teamJson(response, 200, {});
+ }
+ assertDevice(peer);
+ if (
+ path === `${PREFIX}/unpair` &&
+ request.method === 'POST' &&
+ peer.principal.kind === 'botharness-member'
+ ) {
+ await options.team.revoke(peer.principal.grantId);
+ return teamJson(response, 200, { revoked: true });
+ }
+ if (!path.startsWith(`${PREFIX}/api/`) || request.method !== 'POST')
+ throw new TeamError('remote-access/denied');
+ const endpoint = path.slice(`${PREFIX}/api/`.length);
+ const [namespace, method, tail] = endpoint.split('/');
+ const input = rpcSchema.parse(await readTeamBody(request));
+ if (!namespace || !method || tail !== undefined || input.method !== endpoint)
+ throw new TeamError('invalid-input');
+ try {
+ options.team.assertCall(peer.principal, method);
+ const changingPassword = namespace === 'botharness' && method === 'memberPasswordChange';
+ if (changingPassword) transport(request);
+ const invoke = () =>
+ options.gateway.invoke({
+ namespace,
+ method,
+ args: input.payload?.args ?? {},
+ peer,
+ signal: peer.signal,
+ });
+ const value =
+ changingPassword && peer.principal.kind === 'botharness-member'
+ ? await options.team.withPasswordCaller(
+ peer.principal,
+ request.socket.remoteAddress ?? 'unknown',
+ invoke,
+ )
+ : await invoke();
+ teamJson(response, 200, {
+ type: 'server-response',
+ rpcId: input.rpcId,
+ result: { ok: true, value },
+ });
+ } catch (error) {
+ teamJson(response, 200, {
+ type: 'server-response',
+ rpcId: input.rpcId,
+ result: { ok: false, error: failure(error, options.gateway) },
+ });
+ }
+ } catch (error) {
+ deviceFailure(response, error);
+ }
+ },
+ async upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): Promise {
+ let peer: PeerScope;
+ try {
+ if (request.headers.origin || request.url !== `${PREFIX}/api/remote.mux`)
+ throw new TeamError('remote-access/denied');
+ peer = peerFor(request);
+ assertDevice(peer);
+ if (sockets.size >= 64) throw new TeamError('rate-limited');
+ } catch (error) {
+ const code = error instanceof TeamError ? error.code : 'internal';
+ const body = JSON.stringify({ code });
+ socket.end(
+ `HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`,
+ );
+ return;
+ }
+ const server = new WebSocketServer({
+ noServer: true,
+ clientTracking: false,
+ maxPayload: 1024 * 1024,
+ perMessageDeflate: false,
+ });
+ server.handleUpgrade(request, socket, head, (client) => {
+ const streams = new Map();
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ detach();
+ for (const controller of streams.values()) controller.abort();
+ streams.clear();
+ sockets.delete(close);
+ client.terminate();
+ server.close();
+ };
+ const detach = () => peer.signal.removeEventListener('abort', close);
+ sockets.add(close);
+ peer.signal.addEventListener('abort', close, { once: true });
+ client.on('close', close);
+ client.on('error', close);
+ const send = (value: unknown) => {
+ if (client.readyState !== WebSocket.OPEN) return;
+ const text = JSON.stringify(value);
+ if (client.bufferedAmount + Buffer.byteLength(text) > 4 * 1024 * 1024) {
+ close();
+ return;
+ }
+ client.send(text);
+ };
+ client.on('message', (raw, binary) => {
+ let frame: z.infer;
+ try {
+ if (binary) throw new TeamError('invalid-input');
+ frame = frameSchema.parse(JSON.parse(raw.toString()));
+ assertDevice(peer);
+ } catch {
+ close();
+ return;
+ }
+ if (frame.type === 'cancel') {
+ streams.get(frame.streamId)?.abort();
+ streams.delete(frame.streamId);
+ return;
+ }
+ if (streams.has(frame.streamId) || streams.size >= 16 || activeStreams >= 256) {
+ close();
+ return;
+ }
+ const controller = new AbortController();
+ streams.set(frame.streamId, controller);
+ activeStreams++;
+ void (async () => {
+ try {
+ options.team.assertCall(peer.principal, frame.endpoint.split('/').at(-1) ?? '');
+ const signal = AbortSignal.any([peer.signal, controller.signal]);
+ const iterable = await options.gateway.wireStream.open(
+ frame.endpoint,
+ frame.payload,
+ (async function* () {})(),
+ peer,
+ signal,
+ );
+ for await (const value of iterable) {
+ if (signal.aborted) break;
+ assertDevice(peer);
+ send({ type: 'item', streamId: frame.streamId, value });
+ }
+ if (!signal.aborted) send({ type: 'end', streamId: frame.streamId });
+ } catch (error) {
+ if (!controller.signal.aborted)
+ send({
+ type: 'error',
+ streamId: frame.streamId,
+ error: failure(error, options.gateway),
+ });
+ } finally {
+ activeStreams--;
+ if (streams.get(frame.streamId) === controller) streams.delete(frame.streamId);
+ }
+ })();
+ });
+ if (peer.signal.aborted) close();
+ });
+ },
+ close() {
+ for (const close of [...sockets]) close();
+ },
+ };
+}
+export type TeamDeviceHttp = ReturnType;
diff --git a/packages/core/src/team/devices.ts b/packages/core/src/team/devices.ts
new file mode 100644
index 0000000000..f6a7c172ee
--- /dev/null
+++ b/packages/core/src/team/devices.ts
@@ -0,0 +1,86 @@
+import { z } from 'zod';
+import { memberUrls } from './member-urls.js';
+import { TeamError, type TeamService } from './service.js';
+import { pairingLink, qrPath } from '../devices/http.js';
+import type { DevicePairing, HostIdentity } from '../devices/pairing.js';
+import type { EncryptionIdentity } from '../devices/noise-identity.js';
+
+export const deviceSignInSchema = z.object({
+ username: z.string().max(32),
+ password: z.string().max(1024),
+ deviceName: z.string().trim().min(1).max(60),
+ fingerprint: z.string().max(128),
+});
+export interface MemberInvitation {
+ link: string;
+ qr: { size: number; path: string };
+ expiresAt: string;
+}
+export interface MemberPairingOffer extends MemberInvitation {
+ receipt: string;
+}
+export type MemberDeviceSignIn = ReturnType & {
+ host: HostIdentity & { fingerprint: string };
+};
+
+export function createMemberDevices(options: {
+ team: TeamService;
+ pairing: DevicePairing;
+ encryption(): Promise;
+ routes(): Promise;
+ now?: () => number;
+}) {
+ const now = options.now ?? Date.now;
+ const host = async () => ({
+ ...options.pairing.host(),
+ fingerprint: (await options.encryption()).fingerprint,
+ });
+ const routes = async () => memberUrls(await options.routes(), false);
+ return {
+ async invitation(humanId: string): Promise {
+ const member = options.team.member(humanId);
+ if (!member) throw new TeamError('member-not-found');
+ const expiresAt = new Date(now() + 10 * 60_000).toISOString();
+ const payload = {
+ v: 1,
+ host: await host(),
+ routes: await routes(),
+ username: member.username,
+ expiresAt,
+ };
+ const link = `deepseekbot://team?i=${Buffer.from(JSON.stringify(payload)).toString('base64url')}`;
+ return { link, qr: qrPath(link), expiresAt };
+ },
+ async pairingOffer(humanId: string): Promise {
+ const encryption = await options.encryption();
+ const addresses = await routes();
+ const member = options.team.member(humanId);
+ if (!options.team.mode({ humanId }).enabled) throw new TeamError('team-mode-off');
+ if (!member || member.status !== 'active') throw new TeamError('member-suspended');
+ if (member.mustChangePassword) throw new TeamError('password-change-required');
+ const offer = options.pairing.createOffer({ humanId });
+ const link = pairingLink({
+ v: 1,
+ member: true,
+ host: options.pairing.host(),
+ encryption,
+ routes: addresses,
+ offer: offer.offer,
+ expiresAt: offer.expiresAt,
+ });
+ return { link, qr: qrPath(link), expiresAt: offer.expiresAt, receipt: offer.receipt };
+ },
+ async signIn(input: unknown, ip: string, publicKey?: string): Promise {
+ const parsed = deviceSignInSchema.parse(input);
+ const identity = await host();
+ if (parsed.fingerprint !== identity.fingerprint) throw new TeamError('fingerprint-mismatch');
+ const signed = await options.team.signIn(parsed.username, parsed.password, ip, {
+ kind: 'paired-device',
+ name: parsed.deviceName,
+ ...(publicKey === undefined ? {} : { publicKey }),
+ });
+ return { ...options.team.deviceGrantResult(signed, signed.member), host: identity };
+ },
+ };
+}
+export type MemberDevices = ReturnType;
diff --git a/packages/core/src/team/http.ts b/packages/core/src/team/http.ts
index 9c3141b63a..311fa5ef08 100644
--- a/packages/core/src/team/http.ts
+++ b/packages/core/src/team/http.ts
@@ -1,3 +1,5 @@
+import { createTeamDeviceHttp, type TeamDeviceHttp } from './device-http.js';
+import type { MemberDevices } from './devices.js';
import { isIPv4 } from 'node:net';
import { randomBytes } from 'node:crypto';
import type { IncomingMessage, ServerResponse } from 'node:http';
@@ -35,9 +37,11 @@ const rpcSchema = z.discriminatedUnion('op', [
export interface TeamHttp {
handle(request: IncomingMessage, response: ServerResponse): Promise;
close(): Promise;
+ device?: TeamDeviceHttp | undefined;
}
export interface TeamHttpOptions {
team: TeamService;
+ devices?: MemberDevices;
gateway: TypertGateway;
hostName: () => string;
tls: () => boolean;
@@ -52,6 +56,7 @@ function header(request: IncomingMessage, key: string): string | undefined {
export function passwordTransportAllowed(
request: IncomingMessage,
options: Pick,
+ allowInsecureOptIn = true,
): boolean {
const ip = request.socket.remoteAddress;
const address = ip?.startsWith('::ffff:') ? ip.slice(7) : ip;
@@ -62,7 +67,7 @@ export function passwordTransportAllowed(
(!proxy && (ip === '::1' || (isIPv4(address ?? '') && address?.startsWith('127.')))) ||
options.tls() ||
isConnectRequest(request) ||
- options.team.mode(options.team.ownerContext()).insecureHttpAllowed
+ (allowInsecureOptIn && options.team.mode(options.team.ownerContext()).insecureHttpAllowed)
);
}
function token(request: IncomingMessage): string | undefined {
@@ -72,7 +77,7 @@ function token(request: IncomingMessage): string | undefined {
.find((part) => part.startsWith(`${MEMBER_COOKIE}=`))
?.slice(MEMBER_COOKIE.length + 1);
}
-async function body(request: IncomingMessage): Promise {
+export async function readTeamBody(request: IncomingMessage): Promise {
const chunks: Buffer[] = [];
let length = 0;
for await (const chunk of request) {
@@ -87,7 +92,7 @@ async function body(request: IncomingMessage): Promise {
throw new TeamError('invalid-input');
}
}
-function json(response: ServerResponse, status: number, value: unknown): void {
+export function teamJson(response: ServerResponse, status: number, value: unknown): void {
response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
response.end(JSON.stringify(value));
}
@@ -115,6 +120,9 @@ function sameOrigin(request: IncomingMessage, tls: boolean): boolean {
}
export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
+ const device = options.devices
+ ? createTeamDeviceHttp({ ...options, devices: options.devices })
+ : undefined;
const failure = (error: unknown) =>
error instanceof TeamError
? { code: error.code, message: error.code, details: {} }
@@ -148,7 +156,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
}, 30_000);
sweep.unref();
const rpc = async (request: IncomingMessage, peer: PeerScope): Promise => {
- const command = rpcSchema.parse(await body(request));
+ const command = rpcSchema.parse(await readTeamBody(request));
if (command.op === 'call') {
const endpoint = command.path.replace(/^\/api\//u, '');
const [namespace, method, tail] = endpoint.split('/');
@@ -269,9 +277,12 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
};
return {
+ ...(device ? { device } : {}),
async handle(request, response) {
const url = new URL(request.url ?? '/', 'http://member.invalid');
const path = url.pathname;
+ if ([`${TEAM_PATH}/device-sign-in`, `${TEAM_PATH}/device-password`].includes(path) && device)
+ return device.handle(request, response);
const cookie = token(request);
const peer = cookie ? options.team.admit(cookie) : undefined;
try {
@@ -281,7 +292,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
throw new TeamError('insecure-transport');
const input = z
.object({ username: z.string().max(32), password: z.string().max(1024) })
- .parse(await body(request));
+ .parse(await readTeamBody(request));
const result = await options.team.signIn(
input.username,
input.password,
@@ -297,7 +308,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
'set-cookie',
`${MEMBER_COOKIE}=${result.token}; Path=${TEAM_PATH}/; HttpOnly; SameSite=Strict${secure ? '; Secure' : ''}`,
);
- return json(response, 200, {
+ return teamJson(response, 200, {
isolation: 'trial',
humanId: result.member.humanId,
displayName: result.member.displayName,
@@ -314,7 +325,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
next: z.string(),
signOutOthers: z.boolean().optional(),
})
- .parse(await body(request));
+ .parse(await readTeamBody(request));
await options.team.changeWebPassword(
peer.principal,
input.current,
@@ -322,7 +333,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
request.socket.remoteAddress ?? 'unknown',
input.signOutOthers,
);
- return json(response, 200, {});
+ return teamJson(response, 200, {});
}
if (path === `${TEAM_PATH}/sign-out` && request.method === 'POST') {
if (peer?.principal.kind === 'botharness-member')
@@ -331,7 +342,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
'set-cookie',
`${MEMBER_COOKIE}=; Path=${TEAM_PATH}/; HttpOnly; SameSite=Strict; Max-Age=0`,
);
- return json(response, 200, { revoked: true });
+ return teamJson(response, 200, { revoked: true });
}
if ((path === TEAM_PATH || path === `${TEAM_PATH}/`) && request.method === 'GET') {
if (path === TEAM_PATH) {
@@ -386,7 +397,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
}
if (!peer) throw new TeamError('credentials-invalid');
if (path === `${TEAM_PATH}/__share/rpc` && request.method === 'POST')
- return json(response, 200, await rpc(request, peer));
+ return teamJson(response, 200, await rpc(request, peer));
if (path.startsWith(`${TEAM_PATH}/api/`)) {
options.team.assertCall(peer.principal, 'http');
throw new TeamError('remote-access/denied');
@@ -433,7 +444,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
: code === 'internal' || code === 'member-shell-unavailable'
? 503
: 403;
- json(response, status, {
+ teamJson(response, status, {
code,
...(error instanceof TeamError && error.retryAfterSeconds
? { retryAfterSeconds: error.retryAfterSeconds }
@@ -442,6 +453,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp {
}
},
async close() {
+ device?.close();
clearInterval(sweep);
await Promise.all([...new Set([...streams.keys(), ...pending.keys()])].map(cancel));
},
diff --git a/packages/core/src/team/member-methods.ts b/packages/core/src/team/member-methods.ts
index 7db1f3ff9e..5d3d8633d5 100644
--- a/packages/core/src/team/member-methods.ts
+++ b/packages/core/src/team/member-methods.ts
@@ -44,6 +44,8 @@ export const MEMBER_GLOBAL_METHODS = [
'teamOwnerPasswordSet',
'channelPublicSet',
'memberPasswordChange',
+ 'memberInvitation',
+ 'memberPairingOffer',
'memberPasswordReset',
'browsableChannels',
'channelJoin',
diff --git a/packages/core/src/team/mount.ts b/packages/core/src/team/mount.ts
index ba58c1c273..03ccb02987 100644
--- a/packages/core/src/team/mount.ts
+++ b/packages/core/src/team/mount.ts
@@ -1,3 +1,4 @@
+import type { MemberDevices } from './devices.js';
import type { TypertLookup } from '@deepseek-ai/dsh-typert-protocol';
import type { Context } from '@deepseek-ai/cordis';
import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection';
@@ -94,6 +95,7 @@ export function mountTeamGateway(
ctx: Context,
team: TeamService,
hostName: () => string,
+ devices: MemberDevices,
log: (phase: string, facts: Record) => void = () => {},
): TeamHttp | undefined {
const connection: unknown = ctx.get('connection');
@@ -133,6 +135,7 @@ export function mountTeamGateway(
);
const http = createTeamHttp({
team,
+ devices,
gateway,
hostName,
tls: () => web.protocol === 'https:',
diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts
index 5b01e5e9be..32b93c061d 100644
--- a/packages/core/src/team/service.ts
+++ b/packages/core/src/team/service.ts
@@ -202,6 +202,12 @@ export class TeamService {
private readonly limiter: SignInRateLimit;
private peerFactory: ((principal: MemberPrincipal) => PeerScope) | undefined;
private invalidate: () => void = () => {};
+ private devices:
+ | {
+ invitation(humanId: string): Promise;
+ pairingOffer(humanId: string): Promise;
+ }
+ | undefined;
private urls: () => string[] = () => [];
private readonly ensureTob: ((human: HumanContext) => Promise) | undefined;
private readonly now: () => number;
@@ -284,6 +290,29 @@ export class TeamService {
};
}
+ bindDevices(devices: NonNullable): () => void {
+ this.devices = devices;
+ return () => {
+ if (this.devices === devices) this.devices = undefined;
+ };
+ }
+
+ invitation(human: HumanContext, humanId: string) {
+ this.roles.requireManagementTarget(human, humanId);
+ this.active(this.member(humanId));
+ if (!this.devices) throw new TeamError('unavailable');
+ return this.devices.invitation(humanId);
+ }
+
+ pairingOffer(human: HumanContext) {
+ const member = this.member(human.humanId);
+ this.active(member);
+ if (member.owner) throw new TeamError('credentials-invalid');
+ if (member.mustChangePassword) throw new TeamError('password-change-required');
+ if (!this.devices) throw new TeamError('unavailable');
+ return this.devices.pairingOffer(human.humanId);
+ }
+
private settings() {
return z
.object({ enabled: z.coerce.boolean(), insecure_http_allowed: z.coerce.boolean() })
@@ -567,6 +596,7 @@ export class TeamService {
username: string,
password: string,
ip: string,
+ device?: { kind: 'paired-device'; name: string; publicKey?: string },
): Promise<{ token: string; member: TeamMember; peer: PeerScope }> {
if (!this.settings().enabled) throw new TeamError('team-mode-off');
this.passwordAttempt(username, ip);
@@ -582,10 +612,13 @@ export class TeamService {
if (this.credential(member.humanId)?.hash.hash !== credential?.hash.hash)
throw new TeamError('credentials-invalid');
this.active(this.member(member.humanId));
- return { ...this.createGrant(member), member };
+ return { ...this.createGrant(member, device), member };
}
- private createGrant(member: TeamMember): { token: string; peer: PeerScope } {
+ private createGrant(
+ member: TeamMember,
+ device?: { kind: 'paired-device'; name: string; publicKey?: string },
+ ): { token: string; peer: PeerScope } {
this.active(this.member(member.humanId));
if (!this.peerFactory) throw new TeamError('unavailable');
const token = randomBytes(32).toString('base64url');
@@ -594,8 +627,19 @@ export class TeamService {
this.db.transaction(
(db) =>
db
- .prepare('INSERT INTO member_grants VALUES (?, ?, ?, ?, ?, NULL)')
- .run(grantId, tokenHash(token), member.humanId, at, at),
+ .prepare(
+ 'INSERT INTO member_grants(grant_id, token_hash, human_id, created_at, last_seen_at, revoked_at, kind, device_name, public_key) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)',
+ )
+ .run(
+ grantId,
+ tokenHash(token),
+ member.humanId,
+ at,
+ at,
+ device?.kind ?? 'browser-session',
+ device?.name ?? null,
+ device?.publicKey ?? null,
+ ),
['team'],
);
try {
@@ -619,6 +663,109 @@ export class TeamService {
}
}
+ createDeviceGrant(humanId: string, name: string, publicKey?: string) {
+ const member = this.member(humanId);
+ this.active(member);
+ if (member.mustChangePassword) throw new TeamError('password-change-required');
+ return this.deviceGrantResult(
+ this.createGrant(member, {
+ kind: 'paired-device',
+ name,
+ ...(publicKey === undefined ? {} : { publicKey }),
+ }),
+ member,
+ );
+ }
+
+ deviceGrantResult(grant: { token: string; peer: PeerScope }, member: TeamMember) {
+ if (grant.peer.principal.kind !== 'botharness-member') throw new TeamError('forbidden');
+ return {
+ deviceId: grant.peer.principal.grantId,
+ credential: `member.${grant.token}`,
+ humanId: member.humanId,
+ displayName: member.displayName,
+ mustChangePassword: member.mustChangePassword,
+ };
+ }
+
+ admitDevice(authorization: string | undefined, publicKey?: string): PeerScope | undefined {
+ if (publicKey !== undefined && !/^[a-f0-9]{64}$/u.test(publicKey)) return undefined;
+ const match = /^Device member\.([A-Za-z0-9_-]{43})$/u.exec(authorization ?? '');
+ if (!match) return undefined;
+ const row = z
+ .object({ public_key: z.string().nullable() })
+ .optional()
+ .parse(
+ this.db.read((db) =>
+ db
+ .prepare(
+ "SELECT public_key FROM member_grants WHERE token_hash = ? AND kind = 'paired-device' AND revoked_at IS NULL",
+ )
+ .get(tokenHash(match[1]!)),
+ ),
+ );
+ if (
+ !row ||
+ (publicKey !== undefined && row.public_key !== null && row.public_key !== publicKey)
+ )
+ return undefined;
+ const peer = this.admit(match[1]!);
+ if (peer && publicKey !== undefined && row.public_key === null)
+ this.db.transaction(
+ (db) =>
+ db
+ .prepare(
+ 'UPDATE member_grants SET public_key = ? WHERE token_hash = ? AND public_key IS NULL',
+ )
+ .run(publicKey, tokenHash(match[1]!)),
+ ['team'],
+ );
+ return peer;
+ }
+
+ device(deviceId: string) {
+ const row = z
+ .object({
+ grant_id: z.string(),
+ human_id: z.string(),
+ device_name: z.string(),
+ created_at: z.string(),
+ last_seen_at: z.string(),
+ })
+ .optional()
+ .parse(
+ this.db.read((db) =>
+ db
+ .prepare(
+ "SELECT grant_id, human_id, device_name, created_at, last_seen_at FROM member_grants WHERE grant_id = ? AND kind = 'paired-device' AND revoked_at IS NULL",
+ )
+ .get(deviceId),
+ ),
+ );
+ if (
+ !row ||
+ !this.resolve({ kind: 'botharness-member', humanId: row.human_id, grantId: row.grant_id })
+ )
+ return undefined;
+ return {
+ id: row.grant_id,
+ humanId: row.human_id,
+ name: row.device_name,
+ pairedAt: row.created_at,
+ lastSeenAt: row.last_seen_at,
+ };
+ }
+
+ attachDeviceStream(deviceId: string, close: () => void): () => void {
+ const peer = this.peers.get(deviceId);
+ if (!peer || peer.signal.aborted || !this.device(deviceId)) {
+ close();
+ return () => {};
+ }
+ peer.signal.addEventListener('abort', close, { once: true });
+ return () => peer.signal.removeEventListener('abort', close);
+ }
+
resolve(principal: Principal): HumanContext | undefined {
if (principal.kind !== 'botharness-member') return undefined;
const row = this.db.read((db) =>
@@ -1135,7 +1282,9 @@ export class TeamService {
this.db.read((db) =>
db
.prepare(`
- SELECT grant_id AS grantId, '' AS label, 'browser' AS kind, created_at AS createdAt,
+ SELECT grant_id AS grantId, COALESCE(device_name, '') AS label,
+ CASE kind WHEN 'paired-device' THEN 'paired-device' ELSE 'browser' END AS kind,
+ created_at AS createdAt,
last_seen_at AS lastSeenAt, grant_id = ? AS current FROM member_grants
WHERE human_id = ? AND revoked_at IS NULL
UNION ALL
@@ -1152,7 +1301,14 @@ export class TeamService {
if (human.humanId !== humanId) this.roles.require(human, 'members.manage');
const device = this.memberDevices(human, humanId).find((entry) => entry.grantId === grantId);
if (!device) throw new TeamError('device-not-found');
- if (device.kind === 'browser') await this.revoke(grantId);
+ if (
+ this.db.read((db) =>
+ db
+ .prepare('SELECT 1 FROM member_grants WHERE grant_id = ? AND human_id = ?')
+ .get(grantId, humanId),
+ )
+ )
+ await this.revoke(grantId);
else {
if (!this.pairing) throw new TeamError('unavailable');
this.pairing.revoke(grantId);
@@ -1191,7 +1347,8 @@ export class TeamService {
);
this.pairing?.clearOffers();
this.invalidate();
- for (const device of oldDevices) this.pairing?.revoke(device.grantId);
+ for (const device of oldDevices)
+ await this.memberDeviceRevoke(human, human.humanId, device.grantId);
this.log('owner-transferred', { initiator: 'owner', humanId });
return null;
}
diff --git a/packages/core/test/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts
index 537582065d..a5cc09d55e 100644
--- a/packages/core/test/bridge-rpc.test.ts
+++ b/packages/core/test/bridge-rpc.test.ts
@@ -723,6 +723,8 @@ describe('bridge typert service', () => {
'ownerTransfer',
'memberPasswordChange',
'memberPasswordReset',
+ 'memberInvitation',
+ 'memberPairingOffer',
'channelRoleDirectory',
'browsableChannels',
'channelJoin',
diff --git a/packages/core/test/cli-team.test.ts b/packages/core/test/cli-team.test.ts
index 6062c92517..94f55f2a7a 100644
--- a/packages/core/test/cli-team.test.ts
+++ b/packages/core/test/cli-team.test.ts
@@ -429,6 +429,34 @@ describe('Team CLI', () => {
]);
});
+ it('resolves an invitation username and prints only the bridge link JSON', async () => {
+ const f = await host();
+ const result = await run(f.url, ['members', 'invite', 'bob']);
+ expect(result.status).toBe(0);
+ expect(result.output).toEqual({ done: true });
+ expect(f.calls.map((call) => call.path)).toEqual([
+ '/api/botharness/members',
+ '/api/botharness/memberInvitation',
+ ]);
+ expect(f.calls[1]?.input).toMatchObject({ payload: { args: { humanId: 'bob-id' } } });
+ const missing = await run(f.url, ['members', 'invite', 'missing']);
+ expect(missing.status).not.toBe(0);
+ expect(missing.output).toMatchObject({ error: { code: 'member-not-found' } });
+ expect(f.calls).toHaveLength(3);
+ });
+
+ it('dispatches self-pairing under the explicit member and retains the member refusal', async () => {
+ const f = await host();
+ const result = await run(f.url, ['--as', 'bob', 'members', 'pairing-offer']);
+ expect(result.output).toMatchObject({ error: { code: 'remote-access/denied' } });
+ expect(f.calls).toEqual([
+ {
+ path: '/api/botharness/team-as',
+ input: { username: 'bob', namespace: 'botharness', method: 'memberPairingOffer', args: {} },
+ },
+ ]);
+ });
+
it('reads Owner and member passwords only from stdin and requires confirmation for insecure HTTP', async () => {
const f = await host();
expect(
diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts
index af2dd9a748..45d4599fe1 100644
--- a/packages/core/test/plugin.test.ts
+++ b/packages/core/test/plugin.test.ts
@@ -815,6 +815,8 @@ describe('plugin entry', () => {
'ownerTransfer',
'memberPasswordChange',
'memberPasswordReset',
+ 'memberInvitation',
+ 'memberPairingOffer',
'channelRoleDirectory',
'browsableChannels',
'channelJoin',
diff --git a/packages/core/test/schema-migration-ledger.test.ts b/packages/core/test/schema-migration-ledger.test.ts
index 1540757682..c3c691d35e 100644
--- a/packages/core/test/schema-migration-ledger.test.ts
+++ b/packages/core/test/schema-migration-ledger.test.ts
@@ -68,6 +68,44 @@ describe('named schema migration ledger', () => {
expect(readFileSync(path)).toEqual(before);
});
+ it('appends member-devices to a ledger-backed main database without replacing existing browser grants', () => {
+ const home = createTempRoot('bh-ledger-member-devices-');
+ const previous = defineSchemaPlan(
+ plan.migrations.slice(0, plan.generationOf('member-devices') - 2),
+ );
+ expect(previous.migrations.at(-1)?.id).toBe('migration-ledger');
+ const old = trackTestOwner(mountOperationalDatabase({ dshHome: home, schemaPlan: previous }));
+ expect(old.mode).toBe('ready');
+ attachOperationalModule(old, 'team').transaction((db) => {
+ db.prepare('INSERT INTO member_grants VALUES (?, ?, ?, ?, ?, NULL)').run(
+ 'existing-browser',
+ 'token-hash',
+ 'local-human',
+ '2026-11-14',
+ '2026-11-14',
+ );
+ });
+ old.close();
+ const upgraded = open(home);
+ expect(upgraded.mode).toBe('ready');
+ expect(
+ attachOperationalModule(upgraded, 'team').read((db) =>
+ db
+ .prepare(
+ 'SELECT grant_id, kind, device_name, public_key FROM member_grants WHERE grant_id = ?',
+ )
+ .get('existing-browser'),
+ ),
+ ).toEqual({
+ grant_id: 'existing-browser',
+ kind: 'browser-session',
+ device_name: null,
+ public_key: null,
+ });
+ expect(attachOperationalModule(upgraded, 'team').read(ledger)).toEqual(expected);
+ expect(expected.at(-1)?.id).toBe('member-devices');
+ });
+
it.each([1, 25, 78, 116, 149, 153])(
'backfills every applied generation from a pre-ledger generation %i',
(generation) => {
@@ -144,7 +182,9 @@ describe('named schema migration ledger', () => {
it('rolls back backfill, body and generation together on a failed staged migration', () => {
const home = createTempRoot('bh-ledger-rollback-');
- const prefix = defineSchemaPlan(plan.migrations.slice(0, -1));
+ const prefix = defineSchemaPlan(
+ plan.migrations.slice(0, plan.generationOf('migration-ledger') - 2),
+ );
const old = trackTestOwner(mountOperationalDatabase({ dshHome: home, schemaPlan: prefix }));
old.close();
edit(home, (db) => db.exec('DROP TABLE schema_migrations'));
diff --git a/packages/core/test/team-minimal-members.test.ts b/packages/core/test/team-minimal-members.test.ts
index ccbbdc0f6d..3433404aa9 100644
--- a/packages/core/test/team-minimal-members.test.ts
+++ b/packages/core/test/team-minimal-members.test.ts
@@ -311,7 +311,11 @@ describe('M13 upgrade', () => {
const ownerHome = await f.core.tob.ensure(owner);
f.db.transaction((db) => {
db.prepare("INSERT INTO tob_identity VALUES ('member', 'legacy-tob')").run();
- BOT_HARNESS_SCHEMA_PLAN.migrations.at(-1)!.migrate(db);
+ const migration = BOT_HARNESS_SCHEMA_PLAN.migrations.find(
+ (step) => step.id === 'minimal-member',
+ );
+ if (!migration) throw new Error('Missing minimal-member migration');
+ migration.migrate(db);
});
await closes.pop()!();
const restarted = fixture(f.dshHome);
diff --git a/packages/core/test/team-mode.test.ts b/packages/core/test/team-mode.test.ts
index 58ae33bfd5..d1c812b7ab 100644
--- a/packages/core/test/team-mode.test.ts
+++ b/packages/core/test/team-mode.test.ts
@@ -1,9 +1,26 @@
+import {
+ parsePairingLink,
+ redeemPairing,
+ pairHost,
+} from '../../../apps/mobile/src/host/pairing.js';
+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 { noisePublicKey, noiseFingerprint, NOISE_PROTOCOL } from '../src/devices/noise/xk.js';
+import { CONNECT_PROTOCOL } from '../src/devices/noise/channel.js';
+import { randomBytes } from 'node:crypto';
+import { WebSocket } from 'ws';
+import {
+ signInTeamDevice,
+ changeTeamDevicePassword,
+} from '../../../apps/mobile/src/host/team-client.js';
+import type { HostCarrier } from '../../../apps/mobile/src/host/carrier.js';
import { roleModelsSchema } from '../src/team/permissions.js';
import { channelPolicySchema } from '../src/team/channel-contract.js';
import { createAttachmentStore } from '../src/attachments/store.js';
import { DatabaseSync } from 'node:sqlite';
import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js';
-import { createDevicePairing } from '../src/devices/pairing.js';
import { RELATIONSHIP_ACTIONS } from '../src/devices/relationship-http.js';
import { createServer, IncomingMessage, request as httpRequest } from 'node:http';
import { Socket } from 'node:net';
@@ -106,6 +123,41 @@ function teamFixture(options: { urls?: () => string[]; now?: () => number } = {}
purge.close();
db.close();
});
+ const pairing = createDevicePairing({
+ database,
+ hostName: 'Team Host',
+ ownerHumanId: () => team.ownerContext().humanId,
+ ...(options.now ? { now: options.now } : {}),
+ members: {
+ redeem: (id, name, key) => team.createDeviceGrant(id, name, key),
+ admit: (authorization, key) => {
+ const peer = team.admitDevice(authorization, key);
+ return peer?.principal.kind === 'botharness-member'
+ ? team.device(peer.principal.grantId)
+ : undefined;
+ },
+ check: (id) => team.device(id),
+ attach: (id, close) => team.attachDeviceStream(id, close),
+ },
+ });
+ const privateKey = randomBytes(32);
+ const publicKey = noisePublicKey(privateKey);
+ const encryption: import('../src/devices/noise-identity.js').EncryptionIdentity = {
+ protocol: CONNECT_PROTOCOL,
+ noise: NOISE_PROTOCOL,
+ required: true as const,
+ publicKey: Buffer.from(publicKey).toString('hex'),
+ fingerprint: noiseFingerprint(publicKey),
+ };
+ const devices = createMemberDevices({
+ team,
+ pairing,
+ encryption: async () => encryption,
+ routes: async () => ['https://host.test', 'http://127.0.0.1:3080', 'http://192.168.1.2:3080'],
+ ...(options.now ? { now: options.now } : {}),
+ });
+ const unbindDevices = team.bindDevices(devices);
+ closes.push(async () => unbindDevices());
const methods = createBridgeMethodsForHumans({
registry,
channels,
@@ -165,6 +217,10 @@ function teamFixture(options: { urls?: () => string[]; now?: () => number } = {}
const gateway = new TypertGatewayService(ctx, {});
return {
team,
+ devices,
+ pairing,
+ encryption,
+ privateKey,
purge,
root,
channels,
@@ -1739,6 +1795,529 @@ describe('member entry addresses', () => {
});
});
+async function memberDeviceHost(
+ f: ReturnType,
+ options: { tls?: boolean; remote?: boolean } = {},
+) {
+ const http = createTeamHttp({
+ team: f.team,
+ devices: f.devices,
+ gateway: f.gateway,
+ hostName: () => 'Team Host',
+ tls: () => options.tls ?? true,
+ readResource: async () => new Response(''),
+ fetchBundle: async () => new Response(''),
+ });
+ const mintOwner = vi.fn(() => {
+ throw new Error('member-must-never-mint-owner-cookie');
+ });
+ let port = 0;
+ const device = createDeviceGateway({
+ team: http,
+ pairing: f.pairing,
+ port: () => port,
+ authenticatedUrl: mintOwner,
+ });
+ const encrypted = createEncryptedGateway({
+ pairing: f.pairing,
+ memberDevices: f.devices,
+ key: async () => Uint8Array.from(f.privateKey),
+ port: () => port,
+ });
+ 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 }));
+ return;
+ }
+ if (options.remote)
+ Object.defineProperty(req.socket, 'remoteAddress', {
+ value: '192.0.2.5',
+ configurable: true,
+ });
+ void device.handle(req, res);
+ });
+ server.on('upgrade', (req, socket, head) => {
+ if (req.url === '/botharness-device/channel') void encrypted.upgrade(req, socket, head);
+ else void device.upgrade(req, socket, head);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('missing-address');
+ port = address.port;
+ closes.push(async () => {
+ encrypted.close();
+ await http.close();
+ server.closeAllConnections();
+ await new Promise((resolve) => server.close(() => resolve()));
+ });
+ const origin = `http://127.0.0.1:${port}`;
+ const post = (path: string, input: unknown, credential?: string) =>
+ fetch(`${origin}/botharness-device${path}`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(credential ? { authorization: `Device ${credential}` } : {}),
+ },
+ body: JSON.stringify(input),
+ });
+ const signIn = (input: Record = {}) =>
+ post('/team/device-sign-in', {
+ username: 'bob',
+ password: 'initialPassword' in f ? f.initialPassword : '',
+ deviceName: 'Phone',
+ fingerprint: f.encryption.fingerprint,
+ ...input,
+ });
+ const carrier: HostCarrier = {
+ randomBytes: () => randomBytes(32),
+ request: async (url, init) => {
+ const target = new URL(url);
+ const res = await fetch(`${origin}${target.pathname}${target.search}`, {
+ method: init.method,
+ headers: init.headers ?? {},
+ signal: init.signal,
+ ...(typeof init.body === 'string' ? { body: init.body } : {}),
+ });
+ return { status: res.status, text: () => res.text() };
+ },
+ openSocket: (url, events, headers) => {
+ const target = new URL(url);
+ const ws = new WebSocket(`ws://127.0.0.1:${port}${target.pathname}`, {
+ ...(headers ? { headers } : {}),
+ });
+ ws.on('open', events.open);
+ ws.on('message', (raw) => events.message(raw.toString()));
+ ws.on('close', () => events.closed('socket-closed'));
+ ws.on('error', () => events.closed('socket-error'));
+ return { send: (text) => ws.send(text), close: () => ws.close() };
+ },
+ };
+ return { origin, post, signIn, mintOwner, carrier };
+}
+
+describe('member devices', { timeout: 60_000 }, () => {
+ it('issues a secret-free invitation with member-management authority and self-pairing only for the caller', async () => {
+ const f = await enabledFixture();
+ const invitation = await f.team.invitation(owner, f.human.humanId);
+ const payload = JSON.parse(
+ Buffer.from(new URL(invitation.link).searchParams.get('i')!, 'base64url').toString(),
+ );
+ expect(payload).toEqual({
+ v: 1,
+ host: { ...f.pairing.host(), fingerprint: f.encryption.fingerprint },
+ routes: ['https://host.test'],
+ username: 'bob',
+ expiresAt: invitation.expiresAt,
+ });
+ expect(invitation.qr.size).toBeGreaterThan(0);
+ expect(invitation.link).not.toContain(f.initialPassword);
+ expect(() => f.team.invitation(f.human, f.human.humanId)).toThrow('permission-required');
+ expect(() => f.team.pairingOffer(f.human)).toThrow('password-change-required');
+ expect(() => f.team.pairingOffer(owner)).toThrow('credentials-invalid');
+ await f.team.changePassword(f.human, f.initialPassword, 'member-password-1');
+ const offer = await f.team.pairingOffer(f.human);
+ const link = JSON.parse(
+ Buffer.from(new URL(offer.link).searchParams.get('p')!, 'base64url').toString(),
+ );
+ const redeemed = f.pairing.redeem({ offer: link.offer, name: 'Second phone' });
+ expect(redeemed).toMatchObject({
+ ok: true,
+ humanId: f.human.humanId,
+ device: { humanId: f.human.humanId, name: 'Second phone' },
+ });
+ expect(f.pairing.redeem({ offer: link.offer })).toEqual({ ok: false, code: 'offer-invalid' });
+ expect(f.pairing.offerStatus(offer.receipt)).toMatchObject({ state: 'redeemed' });
+ expect(f.pairing.list()).toEqual([]);
+ });
+
+ it('lets a manager invite a covered member while preserving the Admin target ceiling', async () => {
+ const f = await enabledFixture();
+ await f.team.changePassword(f.human, f.initialPassword, 'member-password-1');
+ const manager = f.team.roles.create(owner, 'Manager', ['members.manage', 'dm.humans']);
+ f.team.roles.set(owner, f.human.humanId, [manager.role.roleId]);
+ const alice = await f.team.createMember(owner, 'alice', 'Alice');
+ const signed = await f.team.signIn('bob', 'member-password-1', 'manager-ip');
+ const result = await f.gateway.invoke({
+ namespace: 'botharness',
+ method: 'memberInvitation',
+ args: { humanId: alice.member.humanId },
+ peer: signed.peer,
+ });
+ const invitation = z.object({ link: z.string() }).parse(result);
+ const payload = JSON.parse(
+ Buffer.from(new URL(invitation.link).searchParams.get('i')!, 'base64url').toString(),
+ );
+ expect(payload).toMatchObject({ username: 'alice', host: { id: f.pairing.host().id } });
+ f.team.roles.set(owner, alice.member.humanId, ['admin']);
+ expect(() => f.team.invitation(f.human, alice.member.humanId)).toThrow('permission-required');
+ });
+
+ it('lists and revokes member phone grants through the same management commands as browser sessions', async () => {
+ const f = await enabledFixture();
+ await f.team.changePassword(f.human, f.initialPassword, 'member-password-1');
+ const browser = await f.team.signIn('bob', 'member-password-1', 'browser-ip');
+ const phone = f.team.createDeviceGrant(f.human.humanId, 'Bob phone');
+ const close = vi.fn();
+ f.team.attachDeviceStream(phone.deviceId, close);
+ expect(f.team.memberDevices(f.human, f.human.humanId, phone.deviceId)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ grantId: phone.deviceId,
+ kind: 'paired-device',
+ label: 'Bob phone',
+ current: true,
+ }),
+ expect.objectContaining({ kind: 'browser', current: false }),
+ ]),
+ );
+ await f.team.memberDeviceRevoke(owner, f.human.humanId, phone.deviceId);
+ expect(close).toHaveBeenCalledOnce();
+ expect(f.team.admitDevice(`Device ${phone.credential}`)).toBeUndefined();
+ expect(f.team.admit(browser.token)).toBeDefined();
+ expect(f.team.memberDevices(f.human, f.human.humanId)).not.toEqual(
+ expect.arrayContaining([expect.objectContaining({ grantId: phone.deviceId })]),
+ );
+ expect(f.pairing.list()).toEqual([]);
+ });
+
+ it('keeps ordinary Owner offers pending and refuses to turn member offers into Host relationships', async () => {
+ const f = await enabledFixture();
+ const key = 'ab'.repeat(32);
+ const ownerOffer = f.pairing.createOffer();
+ f.pairing.requestKey({ offer: ownerOffer.offer, publicKey: key });
+ expect(f.pairing.redeem({ offer: ownerOffer.offer, publicKey: key })).toEqual({
+ ok: false,
+ code: 'device-approval-required',
+ });
+ expect(f.pairing.approveKey(ownerOffer.receipt, key)).toBe(true);
+ const ownerDevice = f.pairing.redeem({ offer: ownerOffer.offer, publicKey: key });
+ expect(ownerDevice).toMatchObject({
+ ok: true,
+ credential: expect.not.stringContaining('member.'),
+ });
+ await f.team.changePassword(f.human, f.initialPassword, 'member-password-1');
+ const memberOffer = f.pairing.createOffer({ humanId: f.human.humanId });
+ expect(f.pairing.claimRelationshipOffer(memberOffer.offer)).toBe(false);
+ f.pairing.requestKey({ offer: memberOffer.offer, publicKey: key });
+ expect(f.pairing.redeem({ offer: memberOffer.offer, publicKey: key })).toMatchObject({
+ ok: true,
+ humanId: f.human.humanId,
+ credential: expect.stringContaining('member.'),
+ });
+ });
+
+ it('expires self-pairing offers and rechecks suspension and forced reset at redemption', async () => {
+ let now = Date.now();
+ const f = await enabledFixture({ now: () => now });
+ await f.team.changePassword(f.human, f.initialPassword, 'member-password-1');
+ const token = async () => {
+ const offer = await f.team.pairingOffer(f.human);
+ return JSON.parse(
+ Buffer.from(new URL(offer.link).searchParams.get('p')!, 'base64url').toString(),
+ ).offer;
+ };
+ const expired = await token();
+ now += 10 * 60_000;
+ expect(f.pairing.redeem({ offer: expired })).toEqual({ ok: false, code: 'offer-expired' });
+ const reset = await token();
+ await f.team.resetPassword(owner, f.human.humanId);
+ expect(() => f.pairing.redeem({ offer: reset })).toThrow('password-change-required');
+ const current = await f.team.resetPassword(owner, f.human.humanId);
+ await f.team.changePassword(f.human, current.initialPassword, 'member-password-2');
+ const suspended = await token();
+ await f.team.suspend(owner, f.human.humanId);
+ expect(() => f.pairing.redeem({ offer: suspended })).toThrow('member-suspended');
+ });
+
+ it.each([
+ [{ fingerprint: 'wrong' }, 'fingerprint-mismatch', 403],
+ [{ password: 'wrong' }, 'credentials-invalid', 401],
+ [{ username: 'unknown' }, 'credentials-invalid', 401],
+ [{ username: 'owner' }, 'credentials-invalid', 401],
+ [{ deviceName: '' }, 'invalid-input', 400],
+ ] as const)('refuses device sign-in %j as %s', async (input, code, status) => {
+ const f = await enabledFixture();
+ const host = await memberDeviceHost(f);
+ const response = await host.signIn({ password: f.initialPassword, ...input });
+ expect(response.status).toBe(status);
+ expect(await response.json()).toEqual({ code });
+ expect(host.mintOwner).not.toHaveBeenCalled();
+ });
+
+ it('refuses cleartext and spoofed proxy TLS, mode off, suspension and rate limiting', async () => {
+ const f = await enabledFixture();
+ const host = await memberDeviceHost(f, { tls: false, remote: true });
+ let response = await host.signIn({ password: f.initialPassword });
+ expect(await response.json()).toEqual({ code: 'insecure-transport' });
+ const secure = await memberDeviceHost(f);
+ await f.team.setMode(owner, false);
+ response = await secure.signIn({ password: f.initialPassword });
+ expect(await response.json()).toEqual({ code: 'team-mode-off' });
+ await f.team.setMode(owner, true);
+ await f.team.suspend(owner, f.human.humanId);
+ response = await secure.signIn({ password: f.initialPassword });
+ expect(await response.json()).toEqual({ code: 'member-suspended' });
+ for (let i = 0; i < 4; i++) await secure.signIn({ password: 'wrong' });
+ response = await secure.signIn({ password: f.initialPassword });
+ expect(response.status).toBe(429);
+ expect(await response.json()).toMatchObject({ code: 'rate-limited', retryAfterSeconds: 60 });
+ });
+
+ it('gates every device route and mux until password change, preserves only that grant, and dispatches through the member Peer', async () => {
+ let now = Date.now();
+ const f = await enabledFixture({ now: () => now });
+ const host = await memberDeviceHost(f);
+ const other = await f.team.signIn('bob', f.initialPassword, 'other-ip');
+ const response = await host.signIn({ password: f.initialPassword });
+ expect(response.status).toBe(200);
+ expect(response.headers.has('set-cookie')).toBe(false);
+ const signed = await response.json();
+ expect(signed).toMatchObject({
+ humanId: f.human.humanId,
+ displayName: 'Bob',
+ mustChangePassword: true,
+ });
+ expect(
+ f.database.read((db) =>
+ db
+ .prepare('SELECT kind, device_name, token_hash FROM member_grants WHERE grant_id = ?')
+ .get(signed.deviceId),
+ ),
+ ).toMatchObject({ kind: 'paired-device', device_name: 'Phone' });
+ for (const path of ['/api/botharness/teamMode', '/stream-ticket', '/unpair', '/push']) {
+ const answer = await host.post(path, {}, signed.credential);
+ expect(await answer.json()).toEqual({ code: 'password-change-required' });
+ }
+ let answer = await host.post(
+ '/team/device-password',
+ { current: 'wrong', next: 'member-password-1' },
+ signed.credential,
+ );
+ expect(answer.status).toBe(401);
+ answer = await host.post(
+ '/team/device-password',
+ { current: f.initialPassword, next: 'short' },
+ signed.credential,
+ );
+ expect(answer.status).toBe(400);
+ answer = await host.post(
+ '/team/device-password',
+ { current: f.initialPassword, next: f.initialPassword },
+ signed.credential,
+ );
+ expect(answer.status).toBe(409);
+ now += 60_001;
+ answer = await host.post(
+ '/team/device-password',
+ { current: f.initialPassword, next: 'member-password-1' },
+ signed.credential,
+ );
+ expect(answer.status).toBe(200);
+ expect(f.team.admit(other.token)).toBeUndefined();
+ const own = f.channels.createGroup(f.human, { name: 'Member group', members: [] });
+ const secret = f.channels.createGroup(owner, { name: 'Secret', members: [] });
+ new NativeSession(f.ctx);
+ const rpc = async (namespace: string, method: string, args = {}) =>
+ (
+ await host.post(
+ `/api/${namespace}/${method}`,
+ {
+ type: 'client-request',
+ rpcId: 'device-test',
+ method: `${namespace}/${method}`,
+ payload: { args },
+ },
+ signed.credential,
+ )
+ ).json();
+ expect(await rpc('botharness', 'channelMessages', { channelId: own.id })).toMatchObject({
+ result: { ok: true },
+ });
+ expect(await rpc('botharness', 'channelMessages', { channelId: secret.id })).toMatchObject({
+ result: { ok: false, error: { code: 'remote-access/denied' } },
+ });
+ expect(await rpc('session', 'list')).toMatchObject({
+ result: { ok: false, error: { code: 'remote-access/denied' } },
+ });
+ expect(host.mintOwner).not.toHaveBeenCalled();
+ const peer = f.team.admitDevice(`Device ${signed.credential}`);
+ expect(peer?.principal).toMatchObject({
+ kind: 'botharness-member',
+ humanId: f.human.humanId,
+ grantId: signed.deviceId,
+ });
+ const committed = f.db.diagnostics().metrics.transactionsCommitted;
+ for (let i = 0; i < 20; i++)
+ expect(f.team.admitDevice(`Device ${signed.credential}`)).toBe(peer);
+ expect(f.db.diagnostics().metrics.transactionsCommitted).toBe(committed);
+ await f.team.revoke(signed.deviceId);
+ answer = await host.post('/api/botharness/ping', {}, signed.credential);
+ expect(answer.status).toBe(401);
+ });
+
+ it('signs in and changes the initial password through real Noise with the mobile module, pins its key and never touches Owner cookies', async () => {
+ const f = await enabledFixture();
+ const host = await memberDeviceHost(f);
+ const invitation = {
+ v: 1 as const,
+ host: { ...f.pairing.host(), fingerprint: f.encryption.fingerprint },
+ routes: ['https://habcdefghijkl.deepseekbot.dev'],
+ username: 'bob',
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ };
+ const signed = await signInTeamDevice({
+ carrier: host.carrier,
+ invitation,
+ password: f.initialPassword,
+ deviceName: 'Noise phone',
+ });
+ expect(signed).toMatchObject({
+ ok: true,
+ value: { member: { humanId: f.human.humanId, mustChangePassword: true } },
+ });
+ if (!signed.ok) throw new Error(signed.code);
+ const changed = await changeTeamDevicePassword({
+ carrier: host.carrier,
+ host: signed.value,
+ current: f.initialPassword,
+ next: 'member-password-1',
+ });
+ expect(changed).toMatchObject({ ok: true, value: { member: { mustChangePassword: false } } });
+ expect(f.team.admitDevice(`Device ${signed.value.credential}`, '1'.repeat(64))).toBeUndefined();
+ expect(host.mintOwner).not.toHaveBeenCalled();
+ });
+});
+
+it('uses the member Peer for device mux, refuses native streams and closes the socket on revocation', async () => {
+ const f = await enabledFixture();
+ const host = await memberDeviceHost(f);
+ const signed = await (await host.signIn({ password: f.initialPassword })).json();
+ const refusal = await new Promise((resolve) => {
+ const ws = new WebSocket(
+ host.origin.replace('http:', 'ws:') + '/botharness-device/api/remote.mux',
+ { headers: { authorization: `Device ${signed.credential}` } },
+ );
+ ws.on('unexpected-response', (_request, response) => {
+ let body = '';
+ response.on('data', (data) => (body += String(data)));
+ response.on('end', () => {
+ resolve(body);
+ ws.terminate();
+ });
+ });
+ ws.on('error', () => {});
+ });
+ expect(JSON.parse(refusal)).toEqual({ code: 'password-change-required' });
+ await host.post(
+ '/team/device-password',
+ { current: f.initialPassword, next: 'member-password-1' },
+ signed.credential,
+ );
+ const own = f.channels.createGroup(f.human, { name: 'Own device Channel', members: [] });
+ const secret = f.channels.createGroup(owner, { name: 'Owner Channel', members: [] });
+ const ws = new WebSocket(
+ host.origin.replace('http:', 'ws:') + '/botharness-device/api/remote.mux',
+ { headers: { authorization: `Device ${signed.credential}` } },
+ );
+ closes.push(async () => {
+ ws.terminate();
+ });
+ const frames: unknown[] = [];
+ ws.on('message', (raw) => frames.push(JSON.parse(raw.toString())));
+ await new Promise((resolve, reject) => {
+ ws.once('open', resolve);
+ ws.once('error', reject);
+ });
+ ws.send(
+ JSON.stringify({
+ type: 'open',
+ streamId: 'own',
+ endpoint: 'botharness/followChannel',
+ payload: { args: { channelId: own.id, limit: 10 } },
+ }),
+ );
+ ws.send(
+ JSON.stringify({
+ type: 'open',
+ streamId: 'secret',
+ endpoint: 'botharness/followChannel',
+ payload: { args: { channelId: secret.id, limit: 10 } },
+ }),
+ );
+ ws.send(
+ JSON.stringify({
+ type: 'open',
+ streamId: 'native',
+ endpoint: 'session/list',
+ payload: { args: {} },
+ }),
+ );
+ await vi.waitFor(() => {
+ expect(frames).toContainEqual(expect.objectContaining({ type: 'item', streamId: 'own' }));
+ expect(frames).toContainEqual(
+ expect.objectContaining({
+ type: 'error',
+ streamId: 'secret',
+ error: expect.objectContaining({ code: 'remote-access/denied' }),
+ }),
+ );
+ expect(frames).toContainEqual(expect.objectContaining({ type: 'error', streamId: 'native' }));
+ });
+ const closed = new Promise((resolve) => ws.once('close', () => resolve()));
+ await f.team.revoke(signed.deviceId);
+ await closed;
+ expect(host.mintOwner).not.toHaveBeenCalled();
+}, 60_000);
+
+it('redeems a member self-pairing QR on Host HTTPS through the existing Noise pair protocol without Owner approval', async () => {
+ const f = await enabledFixture();
+ await f.team.changePassword(f.human, f.initialPassword, 'member-password-1');
+ const host = await memberDeviceHost(f);
+ const offer = await f.team.pairingOffer(f.human);
+ const parsed = parsePairingLink(offer.link);
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) throw new Error(parsed.code);
+ const paired = await redeemPairing({
+ payload: parsed.payload,
+ deviceName: 'Second phone',
+ carrier: host.carrier,
+ confirmFingerprint: async (fingerprint) => fingerprint === f.encryption.fingerprint,
+ });
+ expect(paired).toMatchObject({
+ ok: true,
+ host: { member: { humanId: f.human.humanId, mustChangePassword: false } },
+ });
+ if (!paired.ok) throw new Error(paired.code);
+ expect(f.team.admitDevice(`Device ${paired.host.credential}`)?.principal).toMatchObject({
+ kind: 'botharness-member',
+ humanId: f.human.humanId,
+ });
+ expect(f.pairing.offerStatus(offer.receipt)).toMatchObject({
+ state: 'redeemed',
+ deviceId: paired.host.deviceId,
+ });
+ const another = await f.team.pairingOffer(f.human);
+ const save = vi.fn(
+ async (_host: import('../../../apps/mobile/src/host/hosts.js').SavedHost) => {},
+ );
+ expect(
+ await pairHost({
+ text: another.link,
+ method: 'qr',
+ existing: () => paired.host,
+ deviceName: 'Replacement identity',
+ carrier: host.carrier,
+ save,
+ telemetry: { pairing: () => ({ finish: () => {} }) },
+ }),
+ ).toEqual({ ok: true });
+ expect(save).toHaveBeenCalledWith(
+ expect.objectContaining({ member: expect.objectContaining({ humanId: f.human.humanId }) }),
+ );
+ expect(f.pairing.list()).toEqual([]);
+ expect(host.mintOwner).not.toHaveBeenCalled();
+}, 60_000);
describe('M3 Host Roles and devices', { timeout: 60_000 }, () => {
async function actors() {
const f = await enabledFixture();
diff --git a/scripts/schema-migrations.json b/scripts/schema-migrations.json
index 169f399a24..ee1f5a330f 100644
--- a/scripts/schema-migrations.json
+++ b/scripts/schema-migrations.json
@@ -610,5 +610,9 @@
{
"id": "migration-ledger",
"sha256": "c8797dee7988cf70952e32ce178e2f451602fed59e6f22c59bb1e2c905e2b891"
+ },
+ {
+ "id": "member-devices",
+ "sha256": "63577e6e969b47333e63638be4a362adaa11961a520b232413c7a85685ba0301"
}
]