diff --git a/src/mms/net/NetService.ts b/src/mms/net/NetService.ts index 8126ca5b44..3b111c907d 100644 --- a/src/mms/net/NetService.ts +++ b/src/mms/net/NetService.ts @@ -1031,8 +1031,9 @@ export class NetService { ) ) // Signing in to Mousse ID on a computer with no network identity joins the account's network. - // So does a computer whose network is only itself: it joins the account's devices when there - // are any, instead of adding a second, separate network to the account. + // So does a computer that can leave its network without losing anything others rely on: it + // joins the account's devices when there are any, since Mousse ID keeps one devices list per + // account. Only a computer that keeps its network signs in with its own identity. if ( this.hosted && ['net.plus.discover', 'net.plus.login.begin', 'net.plus.login.finish'].includes(method) && @@ -1620,10 +1621,11 @@ export class NetService { await this.firstSession(await this.serial(() => this.join(invite, name, undefined, undefined, true))) }, dropUnsentJoin: () => this.serial(() => this.dropUnsentJoin()), + mayJoinAccount: () => this.aloneOnNetwork(), ownNode: () => (this.hasIdentity() ? this.runtime().identity.self()?.node : undefined), leaveLoneNetwork: () => this.serial(async () => { - if (!this.aloneOnNetwork()) throw new NetError('conflict', 'This computer is no longer alone on its network.') + if (!this.aloneOnNetwork()) throw new NetError('conflict', 'This computer can no longer leave its network.') await this.setAsideNetwork('joined-account') }) } @@ -1635,9 +1637,10 @@ export class NetService { ) } /** - * This computer owns a network that is only itself, with nothing to lose by joining another: it - * may start over (no Space hosted, no other device holding a pass), belongs to no Space, keeps - * no bots in its list and is not signed in to Mousse ID. + * This computer owns a network that nobody else relies on, so it may leave it to join the + * account's devices list: it may start over (no Space hosted, no other device holding a pass), + * belongs to no Space, keeps no bots in its list and is not signed in to Mousse ID. Leaving + * would drop it out of any Space, so a computer in one keeps its network. */ private aloneOnNetwork(): boolean { try { diff --git a/src/mms/net/hosted.ts b/src/mms/net/hosted.ts index badf34bdc3..25d47e1506 100644 --- a/src/mms/net/hosted.ts +++ b/src/mms/net/hosted.ts @@ -79,11 +79,17 @@ export interface HostedNetHost { joinWithInvite(invite: string, name: string): Promise /** Sets aside the keys of a join that never sent its request; queues itself. */ dropUnsentJoin(): Promise + /** + * This computer can leave its network to join the account's devices list without losing + * anything: it hosts or belongs to no Space, no other device holds a pass in its list, it keeps + * no bots and is not signed in to Mousse ID. + */ + mayJoinAccount(): boolean /** This computer's node when it has a network identity. */ ownNode(): NodeId | undefined /** - * Sets aside a network that is only this computer, so it can join the account's network; - * refuses when that is no longer so. Queues itself. + * Sets aside this computer's network so it can join the account's network; refuses when + * `mayJoinAccount` is no longer so. Queues itself. */ leaveLoneNetwork(): Promise } diff --git a/src/mms/net/plus/HostedNetController.ts b/src/mms/net/plus/HostedNetController.ts index b18c9f3861..7bc1dd9cdd 100644 --- a/src/mms/net/plus/HostedNetController.ts +++ b/src/mms/net/plus/HostedNetController.ts @@ -5,7 +5,12 @@ import type { NetLocalMethod, PlusConfiguration, PlusStatus } from '../../../sha import type { HostedNet, HostedNetHost, HostedNetModule, HostedRelayTransports } from '../hosted' import { hostedNotConfigured } from '../hosted' import type { RelayRendezvous } from '../relay/protocol' -import { HostedProfileService, type PlusEnrollmentRequest } from './HostedProfileService' +import { + accountNetworkKept, + HostedProfileService, + isAccountNetwork, + type PlusEnrollmentRequest +} from './HostedProfileService' import { enrollmentJoinUrl, enrollmentMatchCode, @@ -252,7 +257,15 @@ export class HostedNetController implements HostedNet { } else if (!own) await this.host.serial(() => this.host.createIdentity(deviceName)) return this.host.serial(async () => { this.assertTransportCapacity() - const status = await this.service().useGrant(grant.configuration, grant.accessToken, !target, account) + let status: PlusStatus + try { + status = await this.service().useGrant(grant.configuration, grant.accessToken, !target, account) + } catch (error) { + // The account keeps a devices list whose owner computer isn't signed in to Mousse ID right + // now, so there was nothing to join. That computer adds this one once it is open. + if (!target && isAccountNetwork(error)) throw new NetError('authority_offline') + throw error + } await this.useHostedRelay() return status }) @@ -301,7 +314,16 @@ export class HostedNetController implements HostedNet { return this.service().configure(params.configuration as PlusConfiguration) case 'net.plus.login.finish': { this.assertTransportCapacity() - const status = await this.service().finishLogin(String(params.id)) + let status: PlusStatus + try { + status = await this.service().finishLogin(String(params.id)) + } catch (error) { + // Signed in with its own identity, this computer was refused a second devices list. One + // that can leave its network joins the account's list at its next sign-in; one that + // can't keeps working on its own. + if (isAccountNetwork(error) && !this.host.mayJoinAccount()) throw accountNetworkKept() + throw error + } await this.useHostedRelay() return status } @@ -426,8 +448,7 @@ export class HostedNetController implements HostedNet { await this.service().renew() await this.reconcileSpaceRoutes() } catch (error) { - this.host.fail(error) - this.host.emit() + this.failed(error) } await this.refreshDirectPath(true) } @@ -494,9 +515,8 @@ export class HostedNetController implements HostedNet { await this.reconcileSpaceRoutes() }) .catch((error) => { - this.host.fail(error) + this.failed(error) this.armRenewal() - this.host.emit() }) } @@ -523,6 +543,32 @@ export class HostedNetController implements HostedNet { ) } + /** + * Records a failure of background Mousse ID work for `net.status`. A folded devices list is not + * a failure: the account row says it (PlusStatus `reason`), and the link is already dropped. + */ + private failed(error: unknown): void { + if (!isAccountNetwork(error)) this.host.fail(error) + this.host.emit() + } + + /** + * Mousse ID folded this computer's devices list into the account's one list and refuses its + * registration for good. The sign-in is already dropped; the hosted relay goes too, as when + * signed out, so nothing retries it. Signing in again joins the account's list. + */ + private listMerged(): void { + if (this.plusRenewal) clearTimeout(this.plusRenewal) + this.plusRenewal = undefined + this.stopEnrollmentPoll() + this.host.saveHostedTransport(undefined) + void this.host + .serial(() => this.host.restartTransports()) + .catch((error) => this.failed(error)) + .finally(() => this.host.emit()) + this.host.emit() + } + identityReset(): void { if (this.plusRenewal) clearTimeout(this.plusRenewal) this.plusRenewal = undefined @@ -605,10 +651,7 @@ export class HostedNetController implements HostedNet { this.armRenewal() } }) - .catch((error) => { - this.host.fail(error) - this.host.emit() - }) + .catch((error) => this.failed(error)) }, Math.min(left, RENEW_WAKE_CHECK_MS)) this.plusRenewal.unref?.() } @@ -653,10 +696,7 @@ export class HostedNetController implements HostedNet { await this.host .serial(() => this.approveRequest(request)) .then(() => this.requestsApproved.add(request.id)) - .catch((error) => { - this.host.fail(error) - this.host.emit() - }) + .catch((error) => this.failed(error)) } this.setEnrollmentRequests(requests.filter((row) => !this.requestsApproved.has(row.id))) return this.enrollmentList @@ -742,6 +782,7 @@ export class HostedNetController implements HostedNet { delegation: hello.delegation! } }, + listMerged: () => this.listMerged(), adoptRoster: (roster) => { const self = rt.identity.self() const root = self && rt.identity.pinnedRootKey(self.user) diff --git a/src/mms/net/plus/HostedProfileService.ts b/src/mms/net/plus/HostedProfileService.ts index bd009e5de0..b85cbc9211 100644 --- a/src/mms/net/plus/HostedProfileService.ts +++ b/src/mms/net/plus/HostedProfileService.ts @@ -15,6 +15,32 @@ import type { RegistrationResult } from './contracts' const SECRET = 'plus/connector' +/** Set when Mousse ID folded this computer's devices list into the account's one list. */ +const MERGED_SECRET = 'plus/list-merged' +/** + * Mousse ID keeps one devices list per account (its `account_network` refusal): the account already + * has a list on another computer, or this computer's list was folded into it. + */ +export const ACCOUNT_NETWORK = 'account_network' +/** The account has one devices list and this computer can't join it without leaving its own. */ +export const ACCOUNT_NETWORK_KEPT = 'account_network_kept' +const ACCOUNT_NETWORK_MESSAGE = 'Your Mousse ID already has a devices list on another computer.' +/** Whether Mousse ID refused because the account keeps another devices list. */ +export function isAccountNetwork(error: unknown): boolean { + return ( + error instanceof NetError && + error.code === 'conflict' && + (error.details as { reason?: unknown } | undefined)?.reason === ACCOUNT_NETWORK + ) +} +/** The refusal for a computer that keeps its own devices list (it has other devices or Spaces). */ +export function accountNetworkKept(): NetError { + return new NetError( + 'conflict', + 'Your Mousse ID already has a devices list on another computer. This computer has its own devices or Spaces, so it can’t join that list without leaving them. It keeps working on its own.', + { details: { reason: ACCOUNT_NETWORK_KEPT } } + ) +} /** Only the hosted endpoint's transactional rejection releases a durable original. */ class RejectedRendezvous extends NetError { constructor() { @@ -28,9 +54,11 @@ class RejectedRendezvous extends NetError { class RefusedRequest extends NetError { constructor( code: ConstructorParameters[0], - readonly status: number + readonly status: number, + message?: string, + details?: unknown ) { - super(code) + super(code, message, details === undefined ? undefined : { details }) } } interface Stored { @@ -128,6 +156,11 @@ export interface HostedProfileOptions { * Invalid or older rosters are ignored or refused by the identity service. */ adoptRoster?(roster: Signed): boolean + /** + * Mousse ID folded this computer's devices list into the account's one list: the sign-in is + * already dropped here, and the module stops what used it. + */ + listMerged?(): void signal: AbortSignal fetch?: typeof fetch now?(): number @@ -520,7 +553,11 @@ export class HostedProfileService { } : {}) } - : { configured: false, connected: false } + : { + configured: false, + connected: false, + ...(this.options.keys.getSecret(MERGED_SECRET) ? { reason: 'list_merged' as const } : {}) + } } private now(): number { return this.options.now?.() ?? Date.now() @@ -604,16 +641,21 @@ export class HostedProfileService { : response.status === 429 ? 'rate_limited' : 'route_unreachable' - let refused = false + let refusal: unknown try { - refused = - response.status >= 400 && - response.status < 500 && - response.status !== 429 && - typeof JSON.parse(text)?.error?.code === 'string' + refusal = JSON.parse(text)?.error?.code } catch { // A body that is not Mousse ID's error may come from a proxy in front of it. } + if (response.status === 409 && refusal === ACCOUNT_NETWORK) { + this.accountNetwork(token) + throw new RefusedRequest('conflict', 409, ACCOUNT_NETWORK_MESSAGE, { reason: ACCOUNT_NETWORK }) + } + const refused = + response.status >= 400 && + response.status < 500 && + response.status !== 429 && + typeof refusal === 'string' throw refused ? new RefusedRequest(code, response.status) : new NetError(code) } if (response.status === 204) return undefined as T @@ -623,6 +665,20 @@ export class HostedProfileService { throw new NetError('bad_request') } } + /** + * Mousse ID keeps another devices list for this account, so nothing of this sign-in is kept: it + * is dropped as when signed out. Refused with this computer's own credential, its list was folded + * into the account's one list, which status() then says until the next sign-in. + */ + private accountNetwork(token: string): void { + const stored = this.read() + if (!stored) return + const folded = token === stored.connectorToken + this.clear() + if (!folded) return + this.options.keys.putSecret(MERGED_SECRET, canonicalJson({ at: this.now() })) + this.options.listMerged?.() + } private async signed( configuration: PlusConfiguration, purpose: ChallengeStatement['purpose'], @@ -782,6 +838,7 @@ export class HostedProfileService { delete stored.pending delete stored.refused this.save(stored) + if (this.options.keys.getSecret(MERGED_SECRET)) this.options.keys.deleteSecret(MERGED_SECRET) await this.recordDevices(stored, accountToken) return this.status() } @@ -822,7 +879,8 @@ export class HostedProfileService { } catch (error) { // Mousse ID refused a saved renewal, typically because its challenge expired while the // computer slept or was offline. renewOnce dropped it, so sign a fresh one right away. - if (!(error instanceof RefusedRequest) || replayed?.purpose !== 'renew') throw error + if (!(error instanceof RefusedRequest) || replayed?.purpose !== 'renew' || isAccountNetwork(error)) + throw error return this.renewOnce() } // A replayed request carries the roster inside its signed body, which is what the server diff --git a/src/mms/net/registerMethods.ts b/src/mms/net/registerMethods.ts index 5667aeeb51..98a2d7a48f 100644 --- a/src/mms/net/registerMethods.ts +++ b/src/mms/net/registerMethods.ts @@ -478,7 +478,9 @@ const DETAILED_METHODS: ReadonlySet = new Set([ 'net.join.retry', 'net.startOver', 'net.link.make', - 'net.link.paste' + 'net.link.paste', + // Why Mousse ID refused a sign-in: the account keeps one devices list (`account_network`). + 'net.plus.login.finish' ]) function publicError(code: keyof typeof NET_ERRORS, cause?: unknown, details?: unknown): AppError { const entry = NET_ERRORS[code] diff --git a/src/renderer/components/MousseIdAccount.tsx b/src/renderer/components/MousseIdAccount.tsx index 9247f8651c..1a12cdcf0c 100644 --- a/src/renderer/components/MousseIdAccount.tsx +++ b/src/renderer/components/MousseIdAccount.tsx @@ -1,6 +1,6 @@ import { useEffect, useState, type ReactNode } from 'react' import type { PlusStatus } from '../../shared/net/local' -import { formatCountdown, REMOVED_FROM_DEVICES, secondsLeft } from '../lib/plusSignIn' +import { formatCountdown, LIST_MERGED, REMOVED_FROM_DEVICES, secondsLeft } from '../lib/plusSignIn' import { mousseIdName, mousseIdSignedIn, mousseIdPreparation, mousseIdSetupStep, useMousseId, useMousseIdStore, type SignInStart } from '../stores/mousseIdStore' import { MousseIdAvatar } from './MousseIdAvatar' import { SettingsGroup, SettingsRow } from './settings/SettingsRow' @@ -62,7 +62,7 @@ export function MousseIdAccount({ onSetUp, lapsed = false, children }: { onSetUp : status === 'connected' ? <>{[who, plus?.plan].filter(Boolean).join(' · ')}{who || plus?.plan ? ' · ' : ''}Connected : status === 'reconnecting' ? <>{who ? `${who} · ` : ''}Reconnecting{lapsed ? ' · waiting for your other computer to reconnect this one' : ''} : status === 'disconnected' ? `${who ? `${who} · ` : ''}Disconnected · sign in again to reconnect` - : SIGNED_OUT_LINE + : plus?.reason === 'list_merged' ? LIST_MERGED : SIGNED_OUT_LINE const setupStep = !signedIn && !pending && loaded && mousseIdPreparation(net) === 'manual' ? mousseIdSetupStep(net) : '' // A step asked for by Sign in goes once this device is ready or signed in. const setupNote = (!signedIn && mousseIdPreparation(net) !== 'ready' ? needsSetup : '') || setupStep diff --git a/src/renderer/lib/plusSignIn.ts b/src/renderer/lib/plusSignIn.ts index b3704dcaa2..1dc43013ba 100644 --- a/src/renderer/lib/plusSignIn.ts +++ b/src/renderer/lib/plusSignIn.ts @@ -179,6 +179,9 @@ export function mousseIdSetupStep(net?: NetStatus): string { /** This computer was removed from the user's devices; signing in sets its old identity aside and adds it back. */ export const REMOVED_FROM_DEVICES = 'This computer was removed from your devices. Sign in to add it back.' +/** Mousse ID folded this computer's devices list into the account's one list (PlusStatus `reason`). */ +export const LIST_MERGED = 'Your devices are now on one list. Sign in again to join it.' + /** Sign-in failure in words a person can act on. */ export function signInErrorMessage(cause: unknown, origin: string, net?: NetStatus): string { let host = origin @@ -201,9 +204,16 @@ export function signInErrorMessage(cause: unknown, origin: string, net?: NetStat return 'Your other computer signed in to this Mousse ID adds this one to your devices. Open Mousse on it, then sign in again.' case 'expired': return 'The sign-in code expired. Sign in again.' - case 'conflict': + case 'conflict': { + // Mousse ID keeps one devices list per account, and this account's is on another computer. + const reason = ((cause as { details?: { reason?: unknown } } | null)?.details ?? {}).reason + if (reason === 'account_network_kept') + return 'Your Mousse ID already has a devices list on another computer. This computer has its own devices or Spaces, so it can’t join that list without leaving them. It keeps working on its own.' + if (reason === 'account_network') + return 'Your Mousse ID already has a devices list on another computer. Sign in again to join it.' // The daemon words every conflict the same; at sign-in it means this computer still holds the old account. return 'This computer is still set up for an earlier sign-in. Sign out, then sign in again.' + } case 'bad_delegation': case 'revoked': if (net?.self?.removed) return REMOVED_FROM_DEVICES diff --git a/src/shared/net/local.ts b/src/shared/net/local.ts index 12ba3f5559..f08530c68c 100644 --- a/src/shared/net/local.ts +++ b/src/shared/net/local.ts @@ -338,6 +338,11 @@ export interface PlusStatus { * computer signed in. Display-only; it can be out of date until the next sign-in. */ devices?: { used: number; limit: number } + /** + * Why this computer is not signed in. `list_merged`: Mousse ID moved the account's devices onto + * one list and this computer's list was folded into it; signing in again joins that list. + */ + reason?: 'list_merged' } /** A phone asking to join through Mousse ID, as `net.plus.enrollment.requests` returns it. */ export interface PlusEnrollmentRequestView { diff --git a/tests/net/plus/hosted-computer-join.test.ts b/tests/net/plus/hosted-computer-join.test.ts index 5a41b0bbbf..5469d5645a 100644 --- a/tests/net/plus/hosted-computer-join.test.ts +++ b/tests/net/plus/hosted-computer-join.test.ts @@ -33,7 +33,7 @@ type Profile = Awaited> */ async function mousseId(root: string) { const load = (path: string) => import(pathToFileURL(resolve(root, path)).href) - const [{ NetRelayGateway }, { NetHostedService, MemoryNetHostedStore, HostedNetRelayPolicy }, { netRoutes }, { NetLoginService, NetLoginStore }] = + const [{ NetRelayGateway }, { NetHostedService, MemoryNetHostedStore, HostedNetRelayPolicy, NetHostedError }, { netRoutes }, { NetLoginService, NetLoginStore }] = await Promise.all([ load('packages/net-relay/dist/index.js'), load('packages/net-hosted/dist/index.js'), @@ -41,6 +41,7 @@ async function mousseId(root: string) { load('apps/api/dist/net/login.js') ]) const accountId = '08e9bdf6-81f3-4497-815e-7d3d4c398119', + otherAccountId = '3f1c2a9e-7b4d-4e8f-a6c5-1d2e3f4a5b6c', installationId = '5b0f8a4e-1d2c-4c6a-9f3e-2a7b9c1d0e4f' let app: { fetch(request: Request): Promise } | undefined const server = createServer(async (req, res) => { @@ -70,7 +71,7 @@ async function mousseId(root: string) { installationId, audience, credentialKey: randomBytes(32), - accountEligible: async (id: string) => id === accountId + accountEligible: async (id: string) => id === accountId || id === otherAccountId }) const login = new NetLoginService({ store: new NetLoginStore(), @@ -95,6 +96,16 @@ async function mousseId(root: string) { hosted: { entitlements: { get: async () => undefined } } } } as never) + // Mousse ID's app answers a refusal thrown inside a route with its code, as apps/api/src/app.ts does. + const statuses: Record = { + bad_request: 400, unauthorized: 401, forbidden: 403, conflict: 409, expired: 410, revoked: 403, + account_network: 409, not_found: 404, quota_exceeded: 429, unavailable: 503 + } + ;(app as unknown as { onError(handler: (error: unknown) => Response): void }).onError((error) => { + if (!(error instanceof NetHostedError)) throw error + const code = (error as { code: string }).code + return Response.json({ error: { code, message: code, requestId: 'test' } }, { status: statuses[code] ?? 500 }) + }) const gateway = new NetRelayGateway({ audience, installationId, @@ -103,11 +114,16 @@ async function mousseId(root: string) { }) gateway.attach(server) cleanup.push(() => gateway.close()) - return { apiOrigin, accountId, service, login } + return { apiOrigin, accountId, otherAccountId, service, login } } /** Signs a profile in as Settings → Account does, approving in "the browser" at once. */ -async function signIn(fixture: Awaited>, device: Profile, deviceName: string) { +async function signIn( + fixture: Awaited>, + device: Profile, + deviceName: string, + accountId = fixture.accountId +) { const net = device.services.net const configuration = await net.request('net.plus.discover', { apiOrigin: fixture.apiOrigin }) const self = (net.request('net.status', {}) as { self?: { isAuthority?: boolean } }).self @@ -116,7 +132,7 @@ async function signIn(fixture: Awaited>, device: Pro deviceName, bindRoot: !!self?.isAuthority })) as { id: string; userCode: string } - await fixture.login.approval(pending.userCode, { accountId: fixture.accountId, recentAuthAt: Date.now() }, 'approve', 'ada@example.test') + await fixture.login.approval(pending.userCode, { accountId, recentAuthAt: Date.now() }, 'approve', 'ada@example.test') for (let attempt = 0; ; attempt++) { try { return (await net.request('net.plus.login.finish', { id: pending.id })) as { connected: boolean } @@ -227,3 +243,82 @@ it.skipIf(!process.env.MOUSSE_PLUS_ROOT)( }, 90000 ) + +/** + * The state from before Mousse ID kept one devices list per account: `mini` and `desk` each made a + * list of their own on the same account. Mini's list is hidden while desk signs in, so desk binds + * its own, and is then shown again with desk's list made the older one. The fold then runs as at + * load: desk's list is kept and mini's is folded into it. + */ +async function foldedSecondList(fixture: Awaited>, desk: Profile, mini: Profile) { + expect(await signIn(fixture, mini, 'Mac mini')).toMatchObject({ connected: true }) + const own = mini.services.net.runtime().identity.self()! + const hidden = await fixture.service.store.transaction((state: any) => { + const at = state.bindings[own.user].revokedAt + state.bindings[own.user].revokedAt = Date.now() + return at + }) + expect(await signIn(fixture, desk, 'Desk')).toMatchObject({ connected: true }) + const owner = desk.services.net.runtime().identity.self()! + expect(owner.user).not.toBe(own.user) + await fixture.service.store.transaction((state: any) => { + state.bindings[own.user].revokedAt = hidden + state.bindings[owner.user].consentAt = state.bindings[own.user].consentAt - 1000 + expect(fixture.service.foldAccountNetworks(state)).toBe(1) + expect(state.bindings[own.user].foldedInto).toBe(owner.user) + }) + return own +} + +it.skipIf(!process.env.MOUSSE_PLUS_ROOT)( + 'a computer whose devices list was folded learns it at renewal, is signed out, and joins the account’s list when it signs in again', + async () => { + const fixture = await mousseId(process.env.MOUSSE_PLUS_ROOT!) + const desk = await profile({ initialize: false }), + mini = await profile({ initialize: false }) + const own = await foldedSecondList(fixture, desk, mini) + const owner = desk.services.net.runtime().identity.self()! + + await expect(mini.services.net.request('net.plus.renew', {})).rejects.toMatchObject({ code: 'conflict' }) + expect(mini.services.net.request('net.plus.status', {})).toEqual({ + configured: false, + connected: false, + reason: 'list_merged' + }) + + expect(await signIn(fixture, mini, 'Mac mini')).toMatchObject({ connected: true }) + const member = mini.services.net.runtime().identity.self()! + expect(member.user).toBe(owner.user) + expect(member.node).not.toBe(own.node) + expect(mini.services.net.request('net.plus.status', {})).not.toHaveProperty('reason') + const inventory = await fixture.service.inventory({ accountId: fixture.accountId, recentAuthAt: Date.now() }) + expect(inventory.bindings.filter((row: { revokedAt: unknown }) => row.revokedAt === null).map((row: { userId: string }) => row.userId)).toEqual([owner.user]) + expect( + inventory.registrations.filter((row: { revokedAt: unknown }) => row.revokedAt === null).map((row: { nodeId: string }) => row.nodeId).sort() + ).toEqual([owner.node, member.node].sort()) + }, + 90000 +) + +it.skipIf(!process.env.MOUSSE_PLUS_ROOT)( + 'a computer refused at bind because the account keeps another devices list joins that list at its next sign-in', + async () => { + const fixture = await mousseId(process.env.MOUSSE_PLUS_ROOT!) + const desk = await profile({ initialize: false }), + mini = await profile({ initialize: false }) + const own = await foldedSecondList(fixture, desk, mini) + const owner = desk.services.net.runtime().identity.self()! + + // Still signed in here, it signs in with its own identity, and Mousse ID refuses to bind its list again. + await expect(signIn(fixture, mini, 'Mac mini')).rejects.toMatchObject({ + code: 'conflict', + details: { reason: 'account_network' } + }) + expect(mini.services.net.runtime().identity.self()).toMatchObject({ node: own.node }) + expect(mini.services.net.request('net.plus.status', {})).toMatchObject({ configured: false }) + + expect(await signIn(fixture, mini, 'Mac mini')).toMatchObject({ connected: true }) + expect(mini.services.net.runtime().identity.self()!.user).toBe(owner.user) + }, + 90000 +) diff --git a/tests/net/plus/one-devices-list.test.ts b/tests/net/plus/one-devices-list.test.ts new file mode 100644 index 0000000000..cd6b756a49 --- /dev/null +++ b/tests/net/plus/one-devices-list.test.ts @@ -0,0 +1,291 @@ +import { createHash, randomBytes } from 'node:crypto' +import { mkdtempSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { NetService } from '../../../src/mms/net/NetService' +import { mousseIdNetModule } from '../../../src/mms/net/plus/HostedNetController' +import { registerNetMethods } from '../../../src/mms/net/registerMethods' +import { canonicalJson } from '../../../src/mms/net/sync/codec' +import { DomainHandlerRegistry } from '../../../src/mms/protocol/domainRegistry' +import type { HandlerContext } from '../../../src/mms/protocol/handlers' +import type { NetStatus } from '../../../src/shared/net' + +/* + * Mousse ID keeps one devices list per account and refuses a second one with `account_network` + * (HTTP 409), at bind and on the connector calls of a computer whose list it folded. The service + * here is a stand-in written by hand from that contract; tests/net/plus/hosted-computer-join.test.ts + * runs the real one. + * + * Inputs: + * - who signs in: an owner computer with another live device, or in a Space it hosts or belongs to + * (keeps its network), an owner alone on its network (may leave it), an owner still holding an + * earlier sign-in; + * - where the refusal comes: bind with its own identity, bind with a join sign-in when no owner + * computer of the account's list is signed in, renewal of a registration whose list was folded. + */ + +const cleanups: Array<() => Promise | void> = [] +afterEach(async () => { + vi.unstubAllGlobals() + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() +}) + +const configuration = { + apiOrigin: 'http://127.0.0.1:23456', + audience: 'ws://127.0.0.1:23456/v1/net/relay', + installationId: '7e1dc3ea-9146-4a0d-9e83-4a332ef2cbe1', + gatewayId: 'gateway-one' +} +const accountId = '08e9bdf6-81f3-4497-815e-7d3d4c398119' + +/** Mousse ID's net routes, enough to sign in, bind, register and renew; refuses on request. */ +function fakeMousseId() { + const state = { + logins: [] as Array>, + calls: [] as string[], + refuseBind: false, + refuseRenew: false + } + const statements = new Map>() + const refuse = () => + Response.json( + { error: { code: 'account_network', message: 'account_network', requestId: 'req-1' } }, + { status: 409 } + ) + vi.stubGlobal('fetch', async (url: string, init?: RequestInit) => { + const path = new URL(String(url)).pathname, + body = init?.body ? JSON.parse(String(init.body)) : {} + state.calls.push(path) + if (path === '/v1/net/config') + return Response.json({ + installationId: configuration.installationId, + gatewayId: configuration.gatewayId, + relayAudience: configuration.audience + }) + if (path === '/v1/net/login') { + state.logins.push(body) + return Response.json({ + id: `login-${state.logins.length}`, + pollToken: 'p'.repeat(40), + userCode: 'ABCDEF-123456', + verificationUri: `${configuration.apiOrigin}/net-approve?code=ABCDEF-123456`, + expiresAt: Date.now() + 300000, + pollIntervalMs: 2000 + }) + } + if (/^\/v1\/net\/login\/[^/]+$/.test(path)) return Response.json({ status: 'approved' }) + if (path.endsWith('/exchange')) + return Response.json({ accessToken: 'nl_' + 'a'.repeat(40), accountId, expiresAt: Date.now() + 300000 }) + if (path === '/v1/net/challenges') { + const statement = { + v: 1, + domain: 'mousse-plus/net-control/v1', + installationId: configuration.installationId, + audience: configuration.audience, + challengeId: randomBytes(16).toString('hex'), + nonce: randomBytes(32).toString('base64url'), + accountId, + userId: body.userId, + rootKey: body.rootKey, + nodeId: body.purpose === 'bind' ? null : body.nodeId, + purpose: body.purpose, + operationId: body.operationId, + intentHash: createHash('sha256').update(canonicalJson(body.intent)).digest('base64url'), + issuedAt: Date.now(), + expiresAt: Date.now() + 60000 + } + statements.set(statement.challengeId, statement) + return Response.json(statement) + } + if (path === '/v1/net/bindings') return state.refuseBind ? refuse() : Response.json({}) + const registration = () => { + const signed = statements.get(body.challengeId)! + return { + id: 'registration-one', + accountId, + userId: signed.userId, + nodeId: signed.nodeId, + generation: 1, + expiresAt: Date.now() + 600000 + } + } + if (path === '/v1/net/registrations') + return Response.json({ + registration: registration(), + connectorToken: 'c'.repeat(48), + relayAudience: configuration.audience + }) + if (path.endsWith('/renew')) return state.refuseRenew ? refuse() : Response.json(registration()) + if (path === '/v1/net/inventory') + return Response.json({ bindings: [], registrations: [], devices: { used: 1, limit: 5 } }) + return Response.json({ error: { code: 'not_found' } }, { status: 404 }) + }) + return state +} + +type Spaces = Array<{ name: string; host: boolean }> + +function service(spaces: Spaces = []): { net: NetService; path: string } { + const path = mkdtempSync(join(tmpdir(), 'net-one-list-')), + net = new NetService({ + profileDir: path, + hosted: mousseIdNetModule, + composeRuntime: () => ({ close: () => undefined, spaces: () => spaces }) + }) + cleanups.push( + () => rmSync(path, { recursive: true, force: true }), + () => net.shutdown() + ) + return { net, path } +} + +/** An owner computer with networking on, alone on its network. */ +async function lone(name = 'Desk', spaces: Spaces = []) { + const device = service(spaces) + await device.net.request('net.init', { name, listen: true, port: 0 }) + await device.net.request('net.protect', { passphrase: 'test-owner-protection' }) + return device +} + +/** Settings → Account's sign-in calls, as the local IPC carries them to the window. */ +function ipc(net: NetService) { + const registry = new DomainHandlerRegistry() + registerNetMethods(registry, () => net) + const context = { + connection: { + id: 'local-owner', + binding: { profileId: 'selected-profile', epoch: 1 }, + capabilities: new Set(['net.v1']) + } + } as unknown as HandlerContext + return (method: string, params: Record = {}) => + registry.dispatch(context, method as never, { profileId: 'selected-profile', ...params }) +} + +/** Begins and finishes a sign-in approved at once, polling while a join runs. */ +async function signIn(net: NetService, deviceName = 'Desk') { + const call = ipc(net) + const self = (net.request('net.status', {}) as NetStatus).self + const pending = (await call('net.plus.login.begin', { + configuration, + deviceName, + bindRoot: !!self?.isAuthority + })) as { id: string } + for (let attempt = 0; ; attempt++) { + try { + return await call('net.plus.login.finish', { id: pending.id }) + } catch (error) { + if ((error as { code?: string }).code !== 'peer_offline' || attempt > 100) throw error + await new Promise((done) => setTimeout(done, 50)) + } + } +} + +const asideOf = (path: string) => readdirSync(path).filter((name) => name.startsWith('net.')) +const relayRows = (net: NetService) => + (net.request('net.transport.list', {}) as { transports: Array<{ id: string }> }).transports.filter( + (row) => row.id === 'plus-relay' + ) + +it('an owner computer with other devices, refused a second devices list, keeps its network and says why', async () => { + const owner = await lone(), + mini = service() + const invite = (await owner.net.request('bridge.invite', {})) as { invite: string } + await mini.net.request('bridge.join', { invite: invite.invite, name: 'Mac mini' }) + const self = owner.net.runtime().identity.self()! + const mousseId = fakeMousseId() + mousseId.refuseBind = true + + await expect(signIn(owner.net)).rejects.toMatchObject({ + code: 'conflict', + details: { reason: 'account_network_kept' } + }) + + // It signed in with its own identity, since leaving would strand its other device. + expect(mousseId.logins[0]).toMatchObject({ nodeId: self.node }) + expect(mousseId.calls).toContain('/v1/net/bindings') + // Nothing of the refused sign-in is kept, and it works on its own as before. + expect(owner.net.request('net.plus.status', {})).toEqual({ configured: false, connected: false }) + expect(owner.net.runtime().identity.self()).toMatchObject({ node: self.node, isAuthority: true }) + expect(asideOf(owner.path)).toEqual([]) +}, 30000) + +it('a computer alone on its network keeps it when the account’s list has no owner computer signed in to join', async () => { + const desk = await lone() + const self = desk.net.runtime().identity.self()! + const mousseId = fakeMousseId() + mousseId.refuseBind = true + + await expect(signIn(desk.net)).rejects.toMatchObject({ code: 'authority_offline' }) + + expect(mousseId.logins[0]).not.toHaveProperty('nodeId') + expect(desk.net.request('net.plus.status', {})).toEqual({ configured: false, connected: false }) + expect(desk.net.runtime().identity.self()).toMatchObject({ node: self.node, isAuthority: true }) + expect(asideOf(desk.path)).toEqual([]) +}, 30000) + +it('a computer whose devices list was folded drops its sign-in, says so, and joins at its next sign-in', async () => { + const desk = await lone() + const mousseId = fakeMousseId() + expect(await signIn(desk.net)).toMatchObject({ connected: true }) + expect(relayRows(desk.net)).toHaveLength(1) + + mousseId.refuseRenew = true + await expect(ipc(desk.net)('net.plus.renew')).rejects.toMatchObject({ code: 'conflict' }) + + // Signed out, as with Sign out, and the account row can say why. + expect(desk.net.request('net.plus.status', {})).toEqual({ + configured: false, + connected: false, + reason: 'list_merged' + }) + // The hosted relay goes too, once the transports restart without it. + await vi.waitFor(() => expect(relayRows(desk.net)).toEqual([])) + // Not an error of this computer's network. + expect((desk.net.request('net.status', {}) as NetStatus).error).toBeUndefined() + + // The next sign-in is a join sign-in: it joins the account's list when Mousse ID shows one. + const logins = mousseId.logins.length + await ipc(desk.net)('net.plus.login.begin', { configuration, deviceName: 'Desk', bindRoot: true }) + expect(mousseId.logins).toHaveLength(logins + 1) + expect(mousseId.logins.at(-1)).not.toHaveProperty('nodeId') +}, 30000) + +it('a computer still holding an earlier sign-in, refused a second devices list, is told to sign in again to join', async () => { + const desk = await lone() + const mousseId = fakeMousseId() + expect(await signIn(desk.net)).toMatchObject({ connected: true }) + mousseId.refuseBind = true + + // Signed in already, it signs in with its own identity, which binds its own list. + await expect(signIn(desk.net)).rejects.toMatchObject({ + code: 'conflict', + details: { reason: 'account_network' } + }) + expect(mousseId.logins.at(-1)).toHaveProperty('nodeId') + + expect(desk.net.request('net.plus.status', {})).toEqual({ configured: false, connected: false }) + await ipc(desk.net)('net.plus.login.begin', { configuration, deviceName: 'Desk', bindRoot: true }) + expect(mousseId.logins.at(-1)).not.toHaveProperty('nodeId') +}, 30000) + +it.each([ + { role: 'belongs to', spaces: [{ name: 'Team', host: false }] }, + { role: 'hosts', spaces: [{ name: 'Team', host: true }] } +])('an owner computer alone on its network that $role a Space keeps it: refused at bind, it says why', async ({ spaces }) => { + const desk = await lone('Desk', spaces) + const self = desk.net.runtime().identity.self()! + const mousseId = fakeMousseId() + mousseId.refuseBind = true + + // Leaving its network would drop it out of the Space, so it signs in with its own identity. + await expect(signIn(desk.net)).rejects.toMatchObject({ + code: 'conflict', + details: { reason: 'account_network_kept' } + }) + expect(mousseId.logins[0]).toMatchObject({ nodeId: self.node }) + expect(desk.net.request('net.plus.status', {})).toEqual({ configured: false, connected: false }) + expect(desk.net.runtime().identity.self()).toMatchObject({ node: self.node, isAuthority: true }) + expect(asideOf(desk.path)).toEqual([]) +}, 30000) diff --git a/tests/renderer/devicesPage.test.ts b/tests/renderer/devicesPage.test.ts index be2c766fdd..ce36f26bca 100644 --- a/tests/renderer/devicesPage.test.ts +++ b/tests/renderer/devicesPage.test.ts @@ -11,7 +11,12 @@ const { useMousseIdStore } = await import('../../src/renderer/stores/mousseIdSto const policy = { blocked: false, maxPermissionMode: 'accept_edits', terminal: false, editor: false } /** A set-up computer that manages its devices, with one other computer and a phone. */ -const daemon = { error: undefined as string | undefined, removed: false, plus: undefined as Record | undefined } +const daemon = { + error: undefined as string | undefined, + removed: false, + plus: undefined as Record | undefined, + finishError: undefined as unknown +} const request = vi.fn(async (method: string) => { switch (method) { case 'net.status': @@ -20,6 +25,11 @@ const request = vi.fn(async (method: string) => { self: { node: 'nod_self', user: 'usr_a', isAuthority: true, removed: daemon.removed }, peers: [], workOnThreads: true, error: daemon.error } case 'net.plus.status': return daemon.plus + case 'net.plus.login.begin': + return { id: 'login-1', userCode: 'ABCDEF-123456', verificationUri: 'https://id.example/approve', expiresAt: Date.now() + 60_000 } + case 'net.plus.login.finish': + if (daemon.finishError) throw daemon.finishError + return daemon.plus case 'net.transport.list': return { manifests: [], records: {}, settings: {} } case 'net.ssh.list': return { records: [] } case 'bridge.nodes': return { nodes: [ @@ -38,6 +48,7 @@ beforeEach(() => { daemon.error = undefined daemon.removed = false daemon.plus = undefined + daemon.finishError = undefined useMousseIdStore.setState({ runtimeOrigin: '' }) host = document.createElement('div') document.body.append(host) @@ -116,6 +127,32 @@ describe('Settings → Devices', () => { expect([...host.querySelectorAll('button')].map((button) => button.textContent)).toContain('Sign in') }) + it('a computer whose devices list was folded into the account’s one list is told to sign in again to join it', async () => { + daemon.plus = { configured: false, connected: false, reason: 'list_merged' } + useMousseIdStore.setState({ runtimeOrigin: 'https://id.example' }) + await act(async () => root.render(createElement(MousseIdAccount, { onSetUp: () => undefined }))) + await flush() + expect(host.textContent).toContain('Your devices are now on one list. Sign in again to join it.') + expect([...host.querySelectorAll('button')].map((button) => button.textContent)).toContain('Sign in') + }) + + it('a sign-in refused because the account keeps its devices list on another computer says so in plain words', async () => { + daemon.plus = { configured: false, connected: false } + // As the daemon's refusal reaches the window: code, message and details. + daemon.finishError = { code: 'conflict', message: 'The same identifier was used with different content.', details: { reason: 'account_network_kept' } } + useMousseIdStore.setState({ runtimeOrigin: 'https://id.example' }) + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + await act(async () => root.render(createElement(MousseIdAccount, { onSetUp: () => undefined }))) + await flush() + await act(async () => [...host.querySelectorAll('button')].find((button) => button.textContent === 'Sign in')!.click()) + await flush() + open.mockRestore() + const alert = host.querySelector('[role="alert"]')?.textContent ?? '' + expect(alert).toContain('Your Mousse ID already has a devices list on another computer.') + expect(alert).toContain('can’t join that list without leaving them') + expect(alert).not.toMatch(/binding|identifier/i) + }) + it('a disconnected account can be signed out, so signing in to a different one is never stuck', async () => { daemon.plus = { configured: true, connected: false, email: 'me@example.com' } useMousseIdStore.setState({ runtimeOrigin: 'https://id.example' }) diff --git a/tests/renderer/plus-sign-in.test.ts b/tests/renderer/plus-sign-in.test.ts index 737f9611fb..70be0a58af 100644 --- a/tests/renderer/plus-sign-in.test.ts +++ b/tests/renderer/plus-sign-in.test.ts @@ -182,6 +182,15 @@ describe('sign-in errors', () => { .toBe('This computer is still set up for an earlier sign-in. Sign out, then sign in again.') }) + it('says the account keeps one devices list, never "binding", when Mousse ID refuses a second one', () => { + const kept = signInErrorMessage({ code: 'conflict', details: { reason: 'account_network_kept' } }, origin) + expect(kept).toContain('Your Mousse ID already has a devices list on another computer.') + expect(kept).toContain('can’t join that list without leaving them') + const join = signInErrorMessage({ code: 'conflict', details: { reason: 'account_network' } }, origin) + expect(join).toBe('Your Mousse ID already has a devices list on another computer. Sign in again to join it.') + for (const text of [kept, join]) expect(text).not.toMatch(/binding/i) + }) + it('keeps other messages as they are', () => { expect(signInErrorMessage(new Error('Something else'), origin)).toBe('Something else') })