From 2aa7587b33fde5dc7df58f611d50506155ce7b64 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Sat, 14 Nov 2026 10:23:19 +0900 Subject: [PATCH 1/7] feat(team): add member device invitations and sign-in Add member-scoped device grants, password gating and Peer-based HTTP/mux dispatch, with single-use self-pairing and fingerprint-pinned mobile APIs. Persist one confirmed identity per Host and isolate cached member content. Issue: #4146 Agent-Task: codex/local/01a1d77c-e36b-75a0-af02-f39c78f7232d --- apps/mobile/src/host/client.ts | 3 + apps/mobile/src/host/encrypted-carrier.ts | 64 ++- apps/mobile/src/host/host-session.ts | 56 +- apps/mobile/src/host/hosts.ts | 27 +- apps/mobile/src/host/member-identity.ts | 89 ++++ apps/mobile/src/host/pairing.ts | 34 +- apps/mobile/src/host/team-client.ts | 330 ++++++++++++ apps/mobile/src/host/team-invitation.ts | 135 +++++ apps/mobile/test/team-members.test.ts | 328 ++++++++++++ docs/bot-cli.md | 6 + docs/bot-cli.zh.md | 6 + packages/core/src/bots/cli-team.ts | 11 +- packages/core/src/bridge/rpc.ts | 8 + packages/core/src/database/schema-plan.ts | 15 + .../core/src/devices/encrypted-gateway.ts | 45 +- packages/core/src/devices/gateway.ts | 31 +- packages/core/src/devices/http.ts | 3 +- packages/core/src/devices/mount.ts | 42 ++ packages/core/src/devices/pairing.ts | 67 ++- packages/core/src/team/M8.md | 33 ++ packages/core/src/team/bridge.ts | 5 + packages/core/src/team/device-http.ts | 282 ++++++++++ packages/core/src/team/devices.ts | 86 +++ packages/core/src/team/http.ts | 34 +- packages/core/src/team/member-methods.ts | 1 + packages/core/src/team/mount.ts | 3 + packages/core/src/team/service.ts | 154 +++++- packages/core/test/bridge-rpc.test.ts | 2 + packages/core/test/cli-team.test.ts | 28 + packages/core/test/plugin.test.ts | 2 + packages/core/test/team-mode.test.ts | 504 ++++++++++++++++++ 31 files changed, 2388 insertions(+), 46 deletions(-) create mode 100644 apps/mobile/src/host/member-identity.ts create mode 100644 apps/mobile/src/host/team-client.ts create mode 100644 apps/mobile/src/host/team-invitation.ts create mode 100644 apps/mobile/test/team-members.test.ts create mode 100644 packages/core/src/team/M8.md create mode 100644 packages/core/src/team/device-http.ts create mode 100644 packages/core/src/team/devices.ts diff --git a/apps/mobile/src/host/client.ts b/apps/mobile/src/host/client.ts index d1de106a1e..3ead512ca4 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, @@ -204,6 +205,7 @@ export interface HostApiAnswer { } export interface HostClientOptions { + member?: HostMemberIdentity; routePreference?: string; onRoutePreferenceChanged?: (route: string | undefined) => Promise; onRoutesChanged?: (routes: string[]) => Promise; @@ -372,6 +374,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 3e9a1f7408..97609d7f25 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; routePreference?: string; accountOwner?: AccountOwner; connectHost?: string; @@ -41,6 +48,14 @@ export function parseSavedHost(input: unknown): SavedHost | undefined { const value = record(input); 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 ( @@ -91,6 +106,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[], @@ -139,7 +155,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 } : {}), }; @@ -149,10 +165,17 @@ 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 (!hostIdentityMatches(previous, host)) throw new Error('fingerprint-mismatch'); + if (identitySwitchRequired(previous, host) && !confirmedIdentitySwitch) + throw new Error('identity-switch-required'); if (previous?.encryption && previous.encryption.hostKey !== host.encryption?.hostKey) throw new Error('host-key-mismatch'); 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 982c0a258b..412d262b5b 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, @@ -194,7 +204,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?.origin).ok) + payload.routes.some( + (route) => + !checkRoute(route, payload.encryption?.privateRelay?.origin).ok && + !(payload.member && payload.encryption && teamHttpsRoute(route)), + ) ) return { ok: false, code: 'no-route' }; if (payload.enrollment && payload.routes.some((route) => !isConnectRoute(route))) @@ -395,9 +409,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 @@ -678,6 +693,7 @@ function redeemEncryptedRoute( }; const socket = openNoiseSocket({ origin: route, + ...(payload.member ? { trustedHttpsOrigins: payload.routes } : {}), hostId: payload.host.id, encryption, raw: options.carrier, @@ -709,6 +725,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/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/docs/bot-cli.md b/docs/bot-cli.md index 64d9a8b950..79e7a56dc9 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -1933,6 +1933,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 @@ -1952,3 +1954,7 @@ Owner password input is a password with an optional final newline, or JSON `{ "p Non-loopback password sign-in requires Host-known TLS or the encrypted device gateway. The explicitly confirmed `insecure-http` exception permits plain HTTP until disabled. Forwarded protocol headers do not establish TLS. Turning Team mode off revokes member grants and closes their streams while retaining identities, passwords and Channel membership. Re-enabling requires fresh sign-in. `members reset-password --initial-password-file ` is Owner-only recovery when a committed member's one-time password was lost. It writes a new private password file, requires another password change, and revokes that member's grants. An existing output path is refused. Refusals include `owner-protected` and `member-not-found`. A file-write failure after commit returns `initial-password-recovery-required`; retry recovery with a new output path. + +`members invite ` resolves the username as Owner 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 8cab09d3df..7c4b02538c 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -1878,6 +1878,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 @@ -1897,3 +1899,7 @@ Owner 密码从标准输入读取,可带一个结尾换行;修改已有密 非回环地址的密码登录要求 Host 已知的 TLS 或加密设备网关。明确确认的 `insecure-http` 例外允许明文 HTTP,直到关闭;客户端转发的协议请求头不能证明 TLS。关闭团队模式会撤销成员授权并关闭其流,但保留身份、密码和频道成员关系;重新开启后需要重新登录。 `members reset-password --initial-password-file ` 仅供 Owner 恢复已创建但丢失一次性密码的成员。命令写入新的私密密码文件,要求再次改密,并撤销该成员的授权;已有输出文件会被拒绝。拒绝码包括 `owner-protected`、`member-not-found`。提交后的文件写入失败返回 `initial-password-recovery-required`;请使用新的输出路径重试恢复。 + +`members invite ` 由 Owner 将用户名解析为 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 ef757fc3cb..b5059b193d 100644 --- a/packages/core/src/bots/cli-team.ts +++ b/packages/core/src/bots/cli-team.ts @@ -19,7 +19,7 @@ export const TEAM_COMMANDS = [ { command: 'members', description: - 'list | create --username --display-name --initial-password-file | reset-password --initial-password-file | password --password-stdin', + 'list | invite | pairing-offer | create --username --display-name --initial-password-file | reset-password --initial-password-file | password --password-stdin', }, ] as const; @@ -110,6 +110,15 @@ export async function runTeamCommand( } if (command === 'members') { 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' && rest.length === 1 && values['password-stdin']) return rpc( 'memberPasswordChange', diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index b3df11cb08..71f9a5df0f 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -423,6 +423,12 @@ export class BotharnessBridgeService extends TypertRemoteService { ); return unwrapAsync(this.methods.memberPasswordChange({ current, next })); } + memberInvitation(humanId: string) { + return unwrapAsync(this.methods.memberInvitation({ humanId })); + } + memberPairingOffer() { + return unwrapAsync(this.methods.memberPairingOffer({})); + } memberPasswordReset(humanId: string) { return unwrapAsync(this.methods.memberPasswordReset({ humanId })); } @@ -2952,6 +2958,8 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'memberCreate', 'memberPasswordChange', 'memberPasswordReset', + 'memberInvitation', + 'memberPairingOffer', 'publicChannels', 'publicChannelJoin', 'channelPublicSet', diff --git a/packages/core/src/database/schema-plan.ts b/packages/core/src/database/schema-plan.ts index 818398d0fe..3289fd277b 100644 --- a/packages/core/src/database/schema-plan.ts +++ b/packages/core/src/database/schema-plan.ts @@ -3341,6 +3341,20 @@ const TEAM_MEMBERS_MIGRATION: SchemaMigration = { }, }; +const MEMBER_DEVICES_MIGRATION: SchemaMigration = { + generation: 142, + 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, @@ -3482,4 +3496,5 @@ export const BOT_HARNESS_SCHEMA_PLAN = defineSchemaPlan([ DEVICE_FEED_READ_MIGRATION, SOURCE_EVENT_HUMAN_MIGRATION, TEAM_MEMBERS_MIGRATION, + MEMBER_DEVICES_MIGRATION, ]); diff --git a/packages/core/src/devices/encrypted-gateway.ts b/packages/core/src/devices/encrypted-gateway.ts index 6ef10ccb85..cfbb51c01d 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'; @@ -61,6 +63,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' @@ -98,6 +101,7 @@ let nextCallChannel = 0; export function createEncryptedGateway(options: { pairing: DevicePairing; + memberDevices?: MemberDevices; route?: 'connect' | 'lan'; key(): Promise; port(): number; @@ -132,7 +136,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, @@ -567,6 +571,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); @@ -629,6 +638,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 === 'pair') { let offer = field(input, 'offer'); let accountAutoApprove = false; @@ -681,6 +713,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; } @@ -829,7 +868,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 1d77b2b4c4..7321932f1d 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'; @@ -267,11 +268,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( @@ -279,6 +285,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, + }), }), ); }; @@ -644,6 +657,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'); @@ -710,6 +727,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 dd4e912088..93600c3d46 100644 --- a/packages/core/src/devices/http.ts +++ b/packages/core/src/devices/http.ts @@ -32,6 +32,7 @@ const headers = { }; export interface PairingPayload { + member?: true; v: 1 | 2; encryption?: EncryptionIdentity & { loopback?: 'encrypted'; @@ -74,7 +75,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 63ca526170..1713ae5704 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 { mountTeamGateway } from '../team/mount.js'; import type { TeamService } from '../team/service.js'; import type { TeamHttp } from '../team/http.js'; @@ -87,6 +88,7 @@ interface ConnectionLike { interface WebServerLike { readonly port: number; + getOrigin?(): string; register(route: { kind: 'exact' | 'prefix'; path: string; @@ -178,6 +180,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), + }, + } + : {}), record: (event) => write('device-pairing', event.phase, `device-pairing ${detail(event)}`), onRevoked: (deviceId) => { push?.unregister(deviceId); @@ -211,6 +230,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), }); @@ -404,6 +434,7 @@ export function mountDevicePairing( gateway: () => createEncryptedGateway({ pairing, + ...(memberDevices ? { memberDevices } : {}), key: identity.key, port: () => webServer.port, route: 'lan', @@ -546,6 +577,7 @@ export function mountDevicePairing( webCtx.effect(() => () => directPeers.close(), 'botharness: direct device peers'); const encrypted = createEncryptedGateway({ pairing, + ...(memberDevices ? { memberDevices } : {}), key: identity.key, port: () => webServer.port, direct: (input) => directPeers.answer(input), @@ -800,6 +832,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), + ]; const http = createDevicesHttp({ privateConnection, privateTunnel, @@ -871,6 +909,7 @@ export function mountDevicePairing( teamCtx, teamService, () => pairing.host().name, + memberDevices!, (phase, facts) => write( 'team', @@ -895,6 +934,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 621d88a337..4e8abe9236 100644 --- a/packages/core/src/devices/pairing.ts +++ b/packages/core/src/devices/pairing.ts @@ -16,6 +16,7 @@ export interface HostIdentity { export interface PairedDevice { id: string; name: string; + humanId?: string; publicKey?: string; pairedAt: string; lastSeenAt?: string; @@ -46,7 +47,15 @@ export type OfferRefusal = 'offer-invalid' | 'offer-expired' | 'device-approval- 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 }; @@ -68,7 +77,7 @@ export interface PendingDeviceKey { export interface DevicePairing { host(): HostIdentity; - createOffer(binding?: { verifierHash: string; name?: string }): PairingOffer; + createOffer(binding?: { verifierHash?: string; name?: string; humanId?: string }): PairingOffer; offerStatus(receipt: string): OfferStatus; redeem(input: { offer: string; @@ -100,6 +109,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 { @@ -149,6 +174,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin { expiresAt: number; receipt: string; + humanId?: string; verifierHash?: string; name?: string; publicKey?: string; @@ -288,7 +314,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.humanId !== undefined; } return { ok: true, receipt: open.receipt }; }, @@ -323,6 +349,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' }; @@ -354,6 +384,30 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin record({ phase: 'offer-expired' }); return { ok: false, code: 'offer-expired' }; } + if (open.humanId !== undefined) { + const result = options.members?.redeem( + open.humanId, + 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()); @@ -384,6 +438,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' }); @@ -403,6 +461,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 }); @@ -458,6 +518,7 @@ export function createDevicePairing(options: DevicePairingOptions): DevicePairin }, 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..32b3ce7f85 --- /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. Migration 142 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 must list/revoke those grants. This migration must be reconciled with another slice if it also allocates generation 142. + +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 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 f106fc4932..ff1286871d 100644 --- a/packages/core/src/team/bridge.ts +++ b/packages/core/src/team/bridge.ts @@ -45,6 +45,11 @@ export function createTeamBridge(human: HumanContext, team: TeamService | undefi .parse(payload); return service.createMember(human, username, displayName); }), + 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 ac636e3896..a3a61845bf 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'; @@ -36,9 +38,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; @@ -53,6 +57,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; @@ -63,7 +68,7 @@ export function passwordTransportAllowed( (!proxy && (ip === '::1' || (isIPv4(address ?? '') && address?.startsWith('127.')))) || options.tls() || isConnectRequest(request) || - options.team.mode(OWNER_HUMAN_CONTEXT).insecureHttpAllowed + (allowInsecureOptIn && options.team.mode(OWNER_HUMAN_CONTEXT).insecureHttpAllowed) ); } function token(request: IncomingMessage): string | undefined { @@ -73,7 +78,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) { @@ -88,7 +93,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)); } @@ -116,6 +121,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: {} } @@ -149,7 +157,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('/'); @@ -270,9 +278,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 { @@ -282,7 +293,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, @@ -298,7 +309,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, { humanId: result.member.humanId, displayName: result.member.displayName, mustChangePassword: result.member.mustChangePassword, @@ -310,14 +321,14 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp { throw new TeamError('insecure-transport'); const input = z .object({ current: z.string().max(1024), next: z.string() }) - .parse(await body(request)); + .parse(await readTeamBody(request)); await options.team.changeWebPassword( peer.principal, input.current, input.next, request.socket.remoteAddress ?? 'unknown', ); - return json(response, 200, {}); + return teamJson(response, 200, {}); } if (path === `${TEAM_PATH}/sign-out` && request.method === 'POST') { if (peer?.principal.kind === 'botharness-member') @@ -326,7 +337,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) { @@ -380,7 +391,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'); @@ -427,7 +438,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 } @@ -436,6 +447,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 95940cb805..be4eeb4e26 100644 --- a/packages/core/src/team/member-methods.ts +++ b/packages/core/src/team/member-methods.ts @@ -1,6 +1,7 @@ export const MEMBER_GLOBAL_METHODS = [ 'teamMode', 'memberPasswordChange', + 'memberPairingOffer', 'publicChannels', 'publicChannelJoin', 'channels', diff --git a/packages/core/src/team/mount.ts b/packages/core/src/team/mount.ts index 1d00f7a6ec..e9c9fdc111 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 a0819ec579..e2a27ba8ec 100644 --- a/packages/core/src/team/service.ts +++ b/packages/core/src/team/service.ts @@ -82,6 +82,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 now: () => number; private readonly log: (phase: string, facts: Record) => void; @@ -117,6 +123,28 @@ export class TeamService { }; } + bindDevices(devices: NonNullable): () => void { + this.devices = devices; + return () => { + if (this.devices === devices) this.devices = undefined; + }; + } + + invitation(human: HumanContext, humanId: string) { + this.owner(human); + 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.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() }) @@ -323,6 +351,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); @@ -333,10 +362,13 @@ export class TeamService { if (this.credential(member.humanId)?.hash.hash !== credential?.hash.hash) throw new TeamError('credentials-invalid'); this.active(member); - 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'); @@ -345,8 +377,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 { @@ -370,6 +413,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) => diff --git a/packages/core/test/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts index 0bcfabc711..9e58547129 100644 --- a/packages/core/test/bridge-rpc.test.ts +++ b/packages/core/test/bridge-rpc.test.ts @@ -669,6 +669,8 @@ describe('bridge typert service', () => { 'memberCreate', 'memberPasswordChange', 'memberPasswordReset', + 'memberInvitation', + 'memberPairingOffer', 'publicChannels', 'publicChannelJoin', 'channelPublicSet', diff --git a/packages/core/test/cli-team.test.ts b/packages/core/test/cli-team.test.ts index 1a27cef30e..2654411de6 100644 --- a/packages/core/test/cli-team.test.ts +++ b/packages/core/test/cli-team.test.ts @@ -172,6 +172,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 26a8559ab4..ab44034c84 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -592,6 +592,8 @@ describe('plugin entry', () => { 'memberCreate', 'memberPasswordChange', 'memberPasswordReset', + 'memberInvitation', + 'memberPairingOffer', 'publicChannels', 'publicChannelJoin', 'channelPublicSet', diff --git a/packages/core/test/team-mode.test.ts b/packages/core/test/team-mode.test.ts index cef1f344ec..7de17828ad 100644 --- a/packages/core/test/team-mode.test.ts +++ b/packages/core/test/team-mode.test.ts @@ -1,3 +1,21 @@ +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 { createServer, IncomingMessage, request as httpRequest } from 'node:http'; import { Socket } from 'node:net'; import { readFileSync } from 'node:fs'; @@ -71,6 +89,40 @@ function teamFixture(options: { urls?: () => string[]; now?: () => number } = {} await ctx.fiber.dispose(); db.close(); }); + const pairing = createDevicePairing({ + database, + hostName: 'Team Host', + ...(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, @@ -121,6 +173,10 @@ function teamFixture(options: { urls?: () => string[]; now?: () => number } = {} const gateway = new TypertGatewayService(ctx, {}); return { team, + devices, + pairing, + encryption, + privateKey, channels, database, db, @@ -1345,3 +1401,451 @@ describe('member entry addresses', () => { expect(local.team.mode(owner).memberUrls).toEqual([]); }); }); + +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 only to the Owner 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('forbidden'); + 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('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); From c69305168af84cce9d6ec319a489be62b97ebc97 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Sat, 14 Nov 2026 10:28:15 +0900 Subject: [PATCH 2/7] feat(mobile): join a Team mode Host with an invitation and pair your own phones Invitation entry (deep link, pair chooser and pasted link), password sign-in with the forced change on the phone, identity switch confirmation, the signed-in account on the Host connection sheet, and a one-time QR to pair another of the member's phones. Issue: #4146 Agent-Task: claude/local/74a5ee4a-f6fe-4aab-870f-5e465b0b8474 Co-Authored-By: Claude Opus 5.5 --- apps/mobile/app/+native-intent.tsx | 2 + apps/mobile/app/_layout.tsx | 4 + apps/mobile/app/host-connection.tsx | 21 ++ apps/mobile/app/member-pairing.tsx | 103 ++++++++ apps/mobile/app/pair/_layout.tsx | 1 + apps/mobile/app/pair/index.tsx | 9 + apps/mobile/app/pair/team.tsx | 287 +++++++++++++++++++++++ apps/mobile/src/ui/design/tokens.ts | 2 + apps/mobile/src/ui/strings.ts | 99 ++++++++ changes/4146-team-mode-mobile-sign-in.md | 11 + 10 files changed, 539 insertions(+) create mode 100644 apps/mobile/app/member-pairing.tsx create mode 100644 apps/mobile/app/pair/team.tsx create mode 100644 changes/4146-team-mode-mobile-sign-in.md 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} +