Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/mms/net/NetService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) &&
Expand Down Expand Up @@ -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')
})
}
Expand All @@ -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 {
Expand Down
10 changes: 8 additions & 2 deletions src/mms/net/hosted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,17 @@ export interface HostedNetHost {
joinWithInvite(invite: string, name: string): Promise<void>
/** Sets aside the keys of a join that never sent its request; queues itself. */
dropUnsentJoin(): Promise<void>
/**
* 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<void>
}
Expand Down
71 changes: 56 additions & 15 deletions src/mms/net/plus/HostedNetController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
})
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()
})
}

Expand All @@ -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
Expand Down Expand Up @@ -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?.()
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
78 changes: 68 additions & 10 deletions src/mms/net/plus/HostedProfileService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -28,9 +54,11 @@ class RejectedRendezvous extends NetError {
class RefusedRequest extends NetError {
constructor(
code: ConstructorParameters<typeof NetError>[0],
readonly status: number
readonly status: number,
message?: string,
details?: unknown
) {
super(code)
super(code, message, details === undefined ? undefined : { details })
}
}
interface Stored {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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'],
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/mms/net/registerMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,9 @@ const DETAILED_METHODS: ReadonlySet<NetLocalMethod> = 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]
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/components/MousseIdAccount.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -62,7 +62,7 @@ export function MousseIdAccount({ onSetUp, lapsed = false, children }: { onSetUp
: status === 'connected' ? <>{[who, plus?.plan].filter(Boolean).join(' · ')}{who || plus?.plan ? ' · ' : ''}<span className="settings-status-ok">Connected</span></>
: status === 'reconnecting' ? <>{who ? `${who} · ` : ''}<span className="settings-status-warn">Reconnecting</span>{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
Expand Down
12 changes: 11 additions & 1 deletion src/renderer/lib/plusSignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading