fix(cloud): premerge lint: type guards instead of assertions, MFA member fields in their own file, runtime catalog, link-muted button

This commit is contained in:
Neil
2026-11-12 22:47:05 -08:00
parent 97712d56f8
commit ebacf7c882
11 changed files with 75 additions and 50 deletions
@@ -126,7 +126,7 @@ describe('isMfaRequiredRefusal', () => {
{ status: 403 }
)
expect(await isMfaRequiredRefusal(response)).toBe(true)
expect(((await response.json()) as { orgId: string }).orgId).toBe('org_1')
expect(await response.json()).toMatchObject({ orgId: 'org_1' })
})
it('is false for other refusals and for bodies that are not JSON', async () => {
@@ -28,8 +28,13 @@ export const MFA_REQUIRED_REASON = 'mfa_required'
/** Reads a copy of the body, so the caller can still read the response. */
export async function isMfaRequiredRefusal(response: Response): Promise<boolean> {
try {
const body = (await response.clone().json()) as { error?: unknown } | null
return body?.error === MFA_REQUIRED_REASON
const body: unknown = await response.clone().json()
return (
typeof body === 'object' &&
body !== null &&
'error' in body &&
body.error === MFA_REQUIRED_REASON
)
} catch {
return false
}
@@ -160,9 +160,8 @@ export function registerOrcaProfileOrgMemberHandlers(): void {
createOrcaProfileOrg(getProfileUserDataPath(), { name: orgCreateNameFromUnknown(rawArgs) })
)
ipcMain.handle(
'orcaProfiles:accountMfa',
async (): Promise<OrcaAccountMfaResult> => getOrcaProfileAccountMfa(getProfileUserDataPath())
ipcMain.handle('orcaProfiles:accountMfa', async (): Promise<OrcaAccountMfaResult> =>
getOrcaProfileAccountMfa(getProfileUserDataPath())
)
ipcMain.handle(
@@ -175,15 +174,15 @@ export function registerOrcaProfileOrgMemberHandlers(): void {
'orcaProfiles:teamMfaPolicySet',
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPolicySetResult> => {
const { orgId, record } = orgMembersScopedArgs(rawArgs)
const enforce = record.enforce
// Only the fixed choices cross to the server; anything else is refused here.
if (enforce !== 'off' && !ORCA_TEAM_MFA_GRACE_CHOICES.some((choice) => choice === enforce)) {
const enforce: OrcaTeamMfaGrace | 'off' | undefined =
record.enforce === 'off'
? 'off'
: ORCA_TEAM_MFA_GRACE_CHOICES.find((choice) => choice === record.enforce)
if (enforce === undefined) {
return { status: 'failed', error: 'invalid_enforce' }
}
return setOrcaTeamMfaPolicy(getProfileUserDataPath(), {
orgId,
enforce: enforce as OrcaTeamMfaGrace | 'off'
})
return setOrcaTeamMfaPolicy(getProfileUserDataPath(), { orgId, enforce })
}
)
@@ -15,7 +15,8 @@ import { ensureActiveOrcaProfile } from '../profile-index-store'
* a compromised or misconfigured answer cannot send the person to another site to "set up MFA".
*/
export function normalizeAccountMfa(value: unknown, apiBaseUrl: string): OrcaAccountMfa {
const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : {}
const record: Record<string, unknown> =
typeof value === 'object' && value !== null ? { ...value } : {}
const mfa = record.mfa === 'on' || record.mfa === 'off' ? record.mfa : null
let setupUrl: URL | null = null
try {
@@ -46,10 +47,13 @@ async function fetchAccountMfa(
if (!response.ok) {
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
}
return normalizeAccountMfa((await response.json()) as unknown, config.apiBaseUrl)
const body: unknown = await response.json()
return normalizeAccountMfa(body, config.apiBaseUrl)
}
export async function getOrcaProfileAccountMfa(userDataPath: string): Promise<OrcaAccountMfaResult> {
export async function getOrcaProfileAccountMfa(
userDataPath: string
): Promise<OrcaAccountMfaResult> {
const active = ensureActiveOrcaProfile(userDataPath)
// Local dev auth has no server and no factor to enrol.
if (isOrcaCloudDevAuthEnabled()) {
@@ -25,6 +25,10 @@ import {
} from '../cloud-org/profile-cloud-org-members-service'
import { ensureActiveOrcaProfile } from '../profile-index-store'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
const SELF_STATES: readonly OrcaTeamMfaSelfState[] = ['on', 'off', 'pending', 'blocked', 'unknown']
function finiteNumber(value: unknown): number | null {
@@ -47,27 +51,25 @@ export function sameOriginUrl(value: unknown, apiBaseUrl: string): string | null
}
function normalizeDeadline(value: unknown): { enforceAt: number; setAt: number } | null {
const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : null
const record = isRecord(value) ? value : null
const enforceAt = finiteNumber(record?.enforceAt)
const setAt = finiteNumber(record?.setAt)
return enforceAt !== null && setAt !== null ? { enforceAt, setAt } : null
}
export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): OrcaTeamMfaPolicy {
const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : null
const record = isRecord(value) ? value : null
const setupUrl = sameOriginUrl(record?.setupUrl, apiBaseUrl)
if (!record || !setupUrl) {
throw new Error('invalid_orca_team_mfa_policy')
}
const selfRecord =
record.self && typeof record.self === 'object' ? (record.self as Record<string, unknown>) : {}
const selfRecord = isRecord(record.self) ? record.self : {}
// An unrecognized state is "unknown", never "blocked": only the server's word blocks anyone.
const self = SELF_STATES.find((state) => state === selfRecord.mfa) ?? 'unknown'
const pendingMembers = finiteNumber(record.pendingMembers)
const inactive =
record.inactivePolicy && typeof record.inactivePolicy === 'object'
? finiteNumber((record.inactivePolicy as Record<string, unknown>).enforceAt)
: null
const inactive = isRecord(record.inactivePolicy)
? finiteNumber(record.inactivePolicy.enforceAt)
: null
return {
policy: normalizeDeadline(record.policy),
self,
@@ -86,10 +88,10 @@ export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): Orca
}
export function normalizePendingMembers(value: unknown): OrcaTeamMfaPendingMember[] {
const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : null
const record = isRecord(value) ? value : null
const members = Array.isArray(record?.members) ? record.members : []
return members.flatMap((entry): OrcaTeamMfaPendingMember[] => {
const member = entry && typeof entry === 'object' ? (entry as Record<string, unknown>) : null
const member = isRecord(entry) ? entry : null
const email = typeof member?.email === 'string' ? member.email.trim() : ''
if (!member || !email) {
return []
@@ -111,7 +113,8 @@ async function request(url: string, init: RequestInit): Promise<unknown> {
if (!response.ok) {
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
}
return (await response.json()) as unknown
const body: unknown = await response.json()
return body
}
type Unavailable = Extract<
@@ -203,7 +206,8 @@ export async function setOrcaTeamMfaPolicy(
args.enforce === 'off'
? { ...requestInit('GET', token), method: 'DELETE' }
: { ...requestInit('POST', token, { enforce: args.enforce }), method: 'PUT' }
const body = (await request(url('/mfa-policy'), init)) as Record<string, unknown> | null
const answer = await request(url('/mfa-policy'), init)
const body = isRecord(answer) ? answer : null
return {
policy: normalizeDeadline(body?.policy),
pendingMembers: finiteNumber(body?.pendingMembers) ?? 0
@@ -254,10 +258,11 @@ export async function remindOrcaTeamMfa(
const result = await call(
userDataPath,
async (_apiBaseUrl, token, url) => {
const body = (await request(
const answer = await request(
url('/mfa-policy/remind'),
requestInit('POST', token, args.userId ? { userId: args.userId } : {})
)) as Record<string, unknown> | null
)
const body = isRecord(answer) ? answer : null
const delivery: 'log' | 'test-inbox' | 'unknown' =
body?.delivery === 'log' || body?.delivery === 'test-inbox' ? body.delivery : 'unknown'
return { recipients: finiteNumber(body?.recipients) ?? 0, delivery }
@@ -1,6 +1,6 @@
import type { OrcaOrgMemberMfa } from '../../../shared/orca-account-mfa'
import type {
OrcaOrgMember,
OrcaOrgMemberMfa,
OrcaOrgMembersRoster,
OrcaOrgPendingInvite,
OrcaOrgRole
@@ -84,13 +84,7 @@ export function TeamMfaBlockedScreen({
: null}
</p>
{onUsePersonal ? (
<Button
type="button"
variant="link"
size="sm"
className="text-muted-foreground underline"
onClick={onUsePersonal}
>
<Button type="button" variant="link-muted" size="sm" onClick={onUsePersonal}>
{t('auto.components.teamMfa.usePersonal', 'Use my personal account for now')}
</Button>
) : null}
@@ -212,8 +212,8 @@ describe('Require MFA row', () => {
describe('the server refusal in cloud workspace errors', () => {
it('says to set up MFA, never to sign in again', () => {
for (const describe of [describeError, describeInlineError]) {
const message = describe('unauthorized', 'mfa_required', translate)
for (const explain of [describeError, describeInlineError]) {
const message = explain('unauthorized', 'mfa_required', translate)
expect(message).toContain('requires two-factor authentication')
expect(message).not.toMatch(/sign in/i)
}
+12
View File
@@ -1374,6 +1374,18 @@
"unavailableCount_one": "{{count}} unavailable",
"unavailableCount_other": "{{count}} unavailable"
},
"teamMfa": {
"daysLeft_one": "{{count}} day left",
"daysLeft_other": "{{count}} days left",
"nowWarning_one": "{{count}} member doesn’t have it yet and will lose access to this team right away.",
"nowWarning_other": "{{count}} members don’t have it yet and will lose access to this team right away.",
"pendingCount_one": "{{count}} member still needs it",
"pendingCount_other": "{{count}} members still need it",
"reminded_one": "Reminder sent to {{count}} member.",
"reminded_other": "Reminder sent to {{count}} members.",
"soonTitle_one": "{{value0}} requires MFA in {{count}} day",
"soonTitle_other": "{{value0}} requires MFA in {{count}} days"
},
"teammates": {
"daySandboxHours_one": "{{hours}} sandbox hour",
"daySandboxHours_other": "{{hours}} sandbox hours"
+14
View File
@@ -11,3 +11,17 @@ export type OrcaAccountMfaResult =
/** `unsupported`: this Orca Cloud deployment (or local dev auth) has no MFA status. */
| { status: 'unconfigured' | 'reconnect-required' | 'unsupported' }
| { status: 'failed'; error: string }
/**
* A team member's two-factor state as owners and admins see it. Absent for everyone else, and
* for a member the provider said nothing about. 'pending': a team policy requires it by the
* member's `mfaDeadline` and they have not set it up.
*/
export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending'
/** The two-factor fields of a team member (OrcaOrgMember in orca-profiles.ts). */
export type OrcaOrgMemberMfaFields = {
mfa?: OrcaOrgMemberMfa
/** Epoch ms the member must have MFA by; only with `mfa: 'pending'`. */
mfaDeadline?: number
}
+3 -11
View File
@@ -1,3 +1,4 @@
import type { OrcaOrgMemberMfaFields } from './orca-account-mfa'
import './constants'
import { ORCA_BROWSER_PARTITION } from './browser/browser-session-partition'
import type { ExecutionHostId } from './execution-host'
@@ -250,7 +251,8 @@ export type RefreshCurrentOrcaProfileAuthResult =
// Mirror the server’s fixed role enum so UI options cannot drift from accepted API values.
export type OrcaOrgRole = 'owner' | 'admin' | 'member'
export type OrcaOrgMember = {
// Two-factor state (owners and admins only) lives in OrcaOrgMemberMfaFields.
export type OrcaOrgMember = OrcaOrgMemberMfaFields & {
// Provisioned teammates without sign-in have no userId; disable mutations requiring that key.
userId: string | null
email: string
@@ -258,18 +260,8 @@ export type OrcaOrgMember = {
/** Profile picture from the identity provider (https only); avatars fall back to initials. */
pictureUrl?: string
role: OrcaOrgRole
/**
* Whether the member has two-factor authentication. The server sends it to owners and admins
* only, so it is absent for everyone else, and for a member the provider said nothing about.
* 'pending': a team policy requires it by `mfaDeadline` and the member has not set it up.
*/
mfa?: OrcaOrgMemberMfa
/** Epoch ms the member must have MFA by; only with `mfa: 'pending'`. */
mfaDeadline?: number
}
export type OrcaOrgMemberMfa = 'on' | 'off' | 'pending'
export type OrcaOrgPendingInvite = {
email: string
role: OrcaOrgRole