mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
feat(daemon): capture macOS's verdict when a terminal host is refused a folder (#42153)
* feat(daemon): capture macOS's verdict when a terminal host is refused a folder On a confirmed app/host divergence in Documents, Desktop or Downloads, read macOS's own record once per host incarnation and folder class: tccd decisions and kernel sandbox denies for the host pid, host signature checks, host age and origin, earlier good reads, time since wake signals, Full Disk Access, fork-fallback reason, and the class root's dataless, iCloud and volume state (read before the app-side opendir). Telemetry is enum-only in a new daemon_pty_cwd_denial_capture event; raw filtered lines go to a capped local file under userData logs. Every subprocess is bounded and failures are swallowed off the spawn path. * fix(daemon): keep the wake clock Electron-free and avoid casts in the log parser * fix(daemon): tighten denial capture attribution and bounds Snapshot good-read and wake context at the denial, bound the class-root realpath, keep earlier captures when one entry is over the cap, require the app or host in requirement failures, let an explicit pid outrank a shared copy path, and report a capped log read as truncated. * fix(daemon): collect Info requirement checks and claim captures before probing Ask log show for Info records in a 30 s window ending at the denial, claim a helper/class capture before the folder probes and release it when the app is refused too, and report a requirement failure tied only to the shared app identifier as uncorrelated instead of blaming this helper. * fix(daemon): keep folder-denial capture in telemetry labels only Drop the local diagnostics file and stop retaining raw log lines: the parser reads them in memory to derive enums and keeps nothing. * fix(daemon): skip the folder-denial capture when telemetry is off Gate the folder probes and the log/codesign capture on the telemetry client's consent check so opted-out users never have their log read or checks run. * fix(daemon): recheck telemetry consent at every capture stage Run every capture subprocess through a consent-checked runner (now a required probe argument), ask again before and after the identity probe and after the remaining probes, and free the claim when an opt-out stops a capture so a later opt-in can still capture. * fix(daemon): recheck consent after the access reader's lazy import The Full Disk Access reader started after its import resolved without asking again, and its catch swallowed the opt-out; ask after the import and let the opt-out end the capture so its claim is freed. * fix(daemon): report a helper's denial over a later allowed result Overlapping tccd requests can resolve out of order; when any result for the denied folder class is a denial, report it.
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
import type { ForkFallbackValue } from '../../../../shared/daemon-tcc-denial-capture'
|
||||
|
||||
export type MacDaemonForkReason = Exclude<ForkFallbackValue, 'none' | 'unknown'>
|
||||
|
||||
// Why this app's latest launch forked instead of using launchd; null after a launchd launch.
|
||||
let lastMacForkReason: MacDaemonForkReason | null = null
|
||||
|
||||
export function setLastMacDaemonForkReason(reason: MacDaemonForkReason | null): void {
|
||||
lastMacForkReason = reason
|
||||
}
|
||||
|
||||
export function getLastMacDaemonForkReason(): MacDaemonForkReason | null {
|
||||
return lastMacForkReason
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type DaemonChildSpawnOptions
|
||||
} from '../../launch/daemon-launched-child-spawn'
|
||||
import { macDaemonJobLabel } from './macos-daemon-job-label'
|
||||
import { setLastMacDaemonForkReason } from './macos-daemon-fork-reason'
|
||||
import type { DaemonProcessHandle } from '../../launch/daemon-spawner'
|
||||
import { DAEMON_SHUTDOWN_TIMEOUT_MS } from '../../launch/daemon-shutdown-deadline'
|
||||
import {
|
||||
@@ -98,6 +99,7 @@ function fallBackToFork(
|
||||
if (Date.now() > deadlineMs) {
|
||||
throw error
|
||||
}
|
||||
setLastMacDaemonForkReason(reason)
|
||||
console.warn(
|
||||
`[daemon] macOS terminal host fallback reason=${reason}; forking from the app`,
|
||||
error
|
||||
@@ -124,17 +126,20 @@ export async function launchMacDaemonFromStableBundle(
|
||||
options: MacDaemonLaunchOptions,
|
||||
deadlineMs: number
|
||||
): Promise<DaemonProcessHandle | null> {
|
||||
setLastMacDaemonForkReason(null)
|
||||
// GUI login-session watching excludes serve mode.
|
||||
if (
|
||||
process.platform !== 'darwin' ||
|
||||
!options.macosLoginSessionWatch ||
|
||||
!getAppEnvironment().isPackaged()
|
||||
) {
|
||||
setLastMacDaemonForkReason('not-eligible')
|
||||
return null
|
||||
}
|
||||
// Older Macs need the fork path because the helper’s Node cannot load there.
|
||||
const systemVersion = process.getSystemVersion?.()
|
||||
if (!systemVersion || compareDottedVersions(systemVersion, NODE_RUNTIME_DARWIN_MINIMUM_OS) < 0) {
|
||||
setLastMacDaemonForkReason('os-too-old')
|
||||
return null
|
||||
}
|
||||
const label = macDaemonJobLabel(options.userDataPath)
|
||||
|
||||
@@ -26,6 +26,12 @@ import {
|
||||
clearDaemonFolderAccessMismatch,
|
||||
recordDaemonFolderAccessMismatch
|
||||
} from '../permissions/daemon-folder-access-mismatch'
|
||||
import {
|
||||
noteHelperFolderReadable,
|
||||
prepareTccDenialCapture,
|
||||
releaseTccDenialCapture,
|
||||
runTccDenialCapture
|
||||
} from '../permissions/tcc-denial-capture'
|
||||
|
||||
export type DaemonAdoptionOrigin = Pick<
|
||||
EventProps<'daemon_pty_cwd_denied'>,
|
||||
@@ -122,22 +128,35 @@ export async function reportDaemonPtyCwdVerdict(args: {
|
||||
if (!cwd) {
|
||||
return
|
||||
}
|
||||
const deniedAtMs = Date.now()
|
||||
const cwdClass = classifyDaemonPtyCwd(cwd, homedir())
|
||||
const tccFolderClass =
|
||||
process.platform === 'darwin' && isMacTccFolderClass(cwdClass) ? cwdClass : null
|
||||
if (args.cwdReadableByDaemon === true) {
|
||||
clearDaemonFolderAccessMismatch(args.daemonIdentity, cwd)
|
||||
// TCC-gated folders only: elsewhere a readable cwd says nothing about the theory.
|
||||
if (
|
||||
process.platform === 'darwin' &&
|
||||
isMacTccFolderClass(classifyDaemonPtyCwd(cwd, homedir()))
|
||||
) {
|
||||
if (tccFolderClass) {
|
||||
noteHelperFolderReadable(args.daemonIdentity, tccFolderClass)
|
||||
await trackDaemonPtyCwdVerdict('daemon_pty_cwd_readable', cwd, args.pidPath)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The app-side opendir below can materialize a cloud folder, so read its state first.
|
||||
const capture =
|
||||
tccFolderClass && args.cwdReadableByDaemon === false
|
||||
? await prepareTccDenialCapture(args.daemonIdentity, tccFolderClass, deniedAtMs)
|
||||
: null
|
||||
if (!(await hasDaemonPtyCwdDenialDiverged(cwd, args.cwdReadableByDaemon))) {
|
||||
if (capture) {
|
||||
releaseTccDenialCapture(capture)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Show the notice before waiting for the codesign probe.
|
||||
recordDaemonFolderAccessMismatch(args.daemonIdentity, cwd)
|
||||
if (capture) {
|
||||
void runTccDenialCapture(capture)
|
||||
}
|
||||
await trackDaemonPtyCwdVerdict('daemon_pty_cwd_denied', cwd, args.pidPath)
|
||||
} catch {
|
||||
// Best-effort evidence; a spawn must not fail because the notice could not be recorded.
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
// Capture macOS's verdict once per helper incarnation and folder class when a denial is confirmed.
|
||||
|
||||
import { homedir } from 'node:os'
|
||||
import { runProcess } from '@orca/process-host'
|
||||
import { join } from 'node:path'
|
||||
import type { MacTccFolderClass } from '../../../shared/daemon-adoption-telemetry'
|
||||
import {
|
||||
bucketElapsed,
|
||||
bucketGoodReadCount,
|
||||
bucketHelperAge,
|
||||
type FullDiskAccessValue,
|
||||
type HelperOrigin
|
||||
} from '../../../shared/daemon-tcc-denial-capture'
|
||||
import { LOCAL_BUILD_COMPATIBILITY_CONTRACT } from '../../../shared/local-build-compatibility-contract'
|
||||
import type { DeveloperPermissionStatus } from '../../../shared/developer-permissions-types'
|
||||
import type { EventProps } from '../../../shared/telemetry-events'
|
||||
import { msSinceWakeSignal } from '../../power/wake-signal-clock'
|
||||
import { isTelemetryEnabled, track } from '../../telemetry/client'
|
||||
import { inspectMacProcessCodeIdentity } from '../executable-host/macos/daemon-mac-code-identity'
|
||||
import { getLastMacDaemonForkReason } from '../executable-host/macos/macos-daemon-fork-reason'
|
||||
import type { DaemonEndpointIdentity } from '../protocol/daemon-hello-protocol'
|
||||
import { readTccFolderState, type TccFolderState } from './tcc-denial-folder-state'
|
||||
import { readTccLogVerdict } from './tcc-denial-log-verdict'
|
||||
import { checkHelperSignatures } from './tcc-denial-signature-checks'
|
||||
|
||||
const MAX_TRACKED_KEYS = 256
|
||||
const CLASS_ROOT_NAME: Record<MacTccFolderClass, string> = {
|
||||
documents: 'Documents',
|
||||
desktop: 'Desktop',
|
||||
downloads: 'Downloads'
|
||||
}
|
||||
const UNKNOWN_FOLDER_STATE: TccFolderState = {
|
||||
dataless: 'unknown',
|
||||
icloud: 'unknown',
|
||||
volumeType: 'unknown'
|
||||
}
|
||||
const APP_STARTED_AT_MS = Date.now() - process.uptime() * 1_000
|
||||
|
||||
export type TccDenialCaptureStart = {
|
||||
key: string
|
||||
identity: DaemonEndpointIdentity
|
||||
cwdClass: MacTccFolderClass
|
||||
denialAtMs: number
|
||||
folderState: TccFolderState
|
||||
/** Taken at the denial, before any await, so later reads and wakes cannot leak in. */
|
||||
context: Pick<
|
||||
EventProps<'daemon_pty_cwd_denial_capture'>,
|
||||
| 'good_reads_bucket'
|
||||
| 'since_good_read_bucket'
|
||||
| 'since_resume_bucket'
|
||||
| 'since_unlock_bucket'
|
||||
| 'since_user_active_bucket'
|
||||
>
|
||||
}
|
||||
|
||||
type GoodReads = { count: number; lastAtMs: number }
|
||||
|
||||
const goodReads = new Map<string, GoodReads>()
|
||||
const claimedKeys = new Map<string, 'preparing' | 'captured'>()
|
||||
|
||||
function captureKey(identity: DaemonEndpointIdentity, cwdClass: MacTccFolderClass): string {
|
||||
return `${identity.pid}:${identity.startedAtMs}:${identity.launchNonce}:${cwdClass}`
|
||||
}
|
||||
|
||||
function remember<V>(map: Map<string, V>, key: string, value: V): void {
|
||||
map.delete(key)
|
||||
map.set(key, value)
|
||||
// Bounded memory: past 256 helper-class keys the oldest may be captured once more.
|
||||
for (const oldest of map.keys()) {
|
||||
if (map.size <= MAX_TRACKED_KEYS) {
|
||||
break
|
||||
}
|
||||
map.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
class TelemetryOptedOutError extends Error {}
|
||||
|
||||
/** Opted-out users never have their log read or checks run; asked again before every stage. */
|
||||
function requireTelemetryConsent(): void {
|
||||
if (!isTelemetryEnabled()) {
|
||||
throw new TelemetryOptedOutError('telemetry is off')
|
||||
}
|
||||
}
|
||||
|
||||
/** Every capture subprocess runs through this, so a stage added later cannot skip consent. */
|
||||
export const runProcessWithTelemetryConsent: typeof runProcess = (spec, outputCapture) => {
|
||||
try {
|
||||
requireTelemetryConsent()
|
||||
} catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
return runProcess(spec, outputCapture)
|
||||
}
|
||||
|
||||
/** Earlier good reads are the "was readable, then flipped" evidence for this helper. */
|
||||
export function noteHelperFolderReadable(
|
||||
identity: DaemonEndpointIdentity | null,
|
||||
cwdClass: MacTccFolderClass,
|
||||
nowMs: number = Date.now()
|
||||
): void {
|
||||
if (!identity) {
|
||||
return
|
||||
}
|
||||
const key = captureKey(identity, cwdClass)
|
||||
remember(goodReads, key, { count: (goodReads.get(key)?.count ?? 0) + 1, lastAtMs: nowMs })
|
||||
}
|
||||
|
||||
/** Read the folder state before the app-side opendir; null once this helper and class were captured. */
|
||||
export async function prepareTccDenialCapture(
|
||||
identity: DaemonEndpointIdentity | null,
|
||||
cwdClass: MacTccFolderClass,
|
||||
denialAtMs: number,
|
||||
readFolderState: typeof readTccFolderState = readTccFolderState
|
||||
): Promise<TccDenialCaptureStart | null> {
|
||||
// Opted-out users never have their log read or these checks run.
|
||||
if (!identity || !isTelemetryEnabled()) {
|
||||
return null
|
||||
}
|
||||
const key = captureKey(identity, cwdClass)
|
||||
if (claimedKeys.has(key)) {
|
||||
return null
|
||||
}
|
||||
// Claim before the first await: a burst of restored terminals in one folder probes once.
|
||||
remember(claimedKeys, key, 'preparing')
|
||||
const reads = goodReads.get(key)
|
||||
const context: TccDenialCaptureStart['context'] = {
|
||||
good_reads_bucket: bucketGoodReadCount(reads?.count ?? 0),
|
||||
since_good_read_bucket: bucketElapsed(reads ? denialAtMs - reads.lastAtMs : null),
|
||||
since_resume_bucket: bucketElapsed(msSinceWakeSignal('resume', denialAtMs)),
|
||||
since_unlock_bucket: bucketElapsed(msSinceWakeSignal('unlock-screen', denialAtMs)),
|
||||
since_user_active_bucket: bucketElapsed(msSinceWakeSignal('user-did-become-active', denialAtMs))
|
||||
}
|
||||
const folderState = await readFolderState(
|
||||
join(homedir(), CLASS_ROOT_NAME[cwdClass]),
|
||||
cwdClass,
|
||||
runProcessWithTelemetryConsent
|
||||
).catch(() => UNKNOWN_FOLDER_STATE)
|
||||
if (!isTelemetryEnabled()) {
|
||||
claimedKeys.delete(key)
|
||||
return null
|
||||
}
|
||||
return { key, identity, cwdClass, denialAtMs, folderState, context }
|
||||
}
|
||||
|
||||
/** The app was refused too, so nothing diverged: let a later denial on this helper capture. */
|
||||
export function releaseTccDenialCapture(start: TccDenialCaptureStart): void {
|
||||
if (claimedKeys.get(start.key) === 'preparing') {
|
||||
claimedKeys.delete(start.key)
|
||||
}
|
||||
}
|
||||
|
||||
async function readFullDiskAccess(): Promise<FullDiskAccessValue> {
|
||||
let status: DeveloperPermissionStatus
|
||||
try {
|
||||
// Lazy: the status reader reaches the provider modules that import this capture.
|
||||
const { getTerminalHostsFullDiskAccessStatus } =
|
||||
await import('./daemon-full-disk-access-status')
|
||||
// The import is an await: consent may have gone, and the reader probes the host and disk.
|
||||
requireTelemetryConsent()
|
||||
status = await getTerminalHostsFullDiskAccessStatus()
|
||||
} catch (error) {
|
||||
if (error instanceof TelemetryOptedOutError) {
|
||||
throw error
|
||||
}
|
||||
return 'unknown'
|
||||
}
|
||||
return status === 'granted' || status === 'denied' || status === 'unsupported'
|
||||
? status
|
||||
: 'unknown'
|
||||
}
|
||||
|
||||
function helperOriginOf(identity: DaemonEndpointIdentity): HelperOrigin {
|
||||
if (!Number.isFinite(identity.startedAtMs) || identity.startedAtMs <= 0) {
|
||||
return 'unknown'
|
||||
}
|
||||
return identity.startedAtMs < APP_STARTED_AT_MS ? 'adopted' : 'spawned'
|
||||
}
|
||||
|
||||
/** Never throws, never blocks a spawn; at most one capture per helper incarnation and folder class. */
|
||||
export async function runTccDenialCapture(start: TccDenialCaptureStart): Promise<void> {
|
||||
if (claimedKeys.get(start.key) === 'captured') {
|
||||
return
|
||||
}
|
||||
remember(claimedKeys, start.key, 'captured')
|
||||
try {
|
||||
const { identity, cwdClass, denialAtMs, folderState } = start
|
||||
// Consent can be withdrawn at any await (the app-side read can wait on a prompt), so every
|
||||
// stage asks again; the shared identity probe is gated here, the rest through the runner.
|
||||
requireTelemetryConsent()
|
||||
const helperPath =
|
||||
(await inspectMacProcessCodeIdentity(identity.pid)).executablePath ??
|
||||
identity.spawnerExecPath ??
|
||||
null
|
||||
requireTelemetryConsent()
|
||||
const [log, signatures, fullDiskAccess] = await Promise.all([
|
||||
readTccLogVerdict(
|
||||
denialAtMs,
|
||||
{
|
||||
helperPid: identity.pid,
|
||||
helperPath,
|
||||
appId: LOCAL_BUILD_COMPATIBILITY_CONTRACT.appId,
|
||||
cwdClass
|
||||
},
|
||||
runProcessWithTelemetryConsent
|
||||
),
|
||||
checkHelperSignatures(identity.pid, helperPath, runProcessWithTelemetryConsent),
|
||||
readFullDiskAccess()
|
||||
])
|
||||
requireTelemetryConsent()
|
||||
const origin = helperOriginOf(identity)
|
||||
const props: EventProps<'daemon_pty_cwd_denial_capture'> = {
|
||||
cwd_class: cwdClass,
|
||||
log_access: log.logAccess,
|
||||
tccd_asked: log.tccdAsked,
|
||||
auth_value: log.authValue,
|
||||
auth_reason: log.authReason,
|
||||
service: log.service,
|
||||
requirement_failure: log.requirementFailure,
|
||||
kernel_deny: log.kernelDeny,
|
||||
live_signature: signatures.live,
|
||||
disk_copy_signature: signatures.diskCopy,
|
||||
helper_age_bucket: bucketHelperAge(
|
||||
identity.startedAtMs > 0 ? denialAtMs - identity.startedAtMs : null
|
||||
),
|
||||
helper_origin: origin,
|
||||
...start.context,
|
||||
full_disk_access: fullDiskAccess,
|
||||
// An adopted helper was launched by an earlier app process whose reason is gone.
|
||||
fork_fallback: origin === 'spawned' ? (getLastMacDaemonForkReason() ?? 'none') : 'unknown',
|
||||
folder_dataless: folderState.dataless,
|
||||
folder_icloud: folderState.icloud,
|
||||
volume_type: folderState.volumeType
|
||||
}
|
||||
track('daemon_pty_cwd_denial_capture', props)
|
||||
} catch (error) {
|
||||
// An opted-out capture was not taken, so a later denial may still capture after opt-in.
|
||||
if (error instanceof TelemetryOptedOutError) {
|
||||
claimedKeys.delete(start.key)
|
||||
}
|
||||
// Diagnostics are best-effort; a failed capture must not reach terminal creation.
|
||||
}
|
||||
}
|
||||
|
||||
export function resetTccDenialCaptureForTests(): void {
|
||||
goodReads.clear()
|
||||
claimedKeys.clear()
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Folder-class root state read before the app's own opendir can materialize or change it.
|
||||
|
||||
import { realpath } from 'node:fs/promises'
|
||||
import type { runProcess } from '@orca/process-host'
|
||||
import type { MacTccFolderClass } from '../../../shared/daemon-adoption-telemetry'
|
||||
import type {
|
||||
FolderFlag,
|
||||
IcloudManaged,
|
||||
VolumeType
|
||||
} from '../../../shared/daemon-tcc-denial-capture'
|
||||
|
||||
const PROBE_TIMEOUT_MS = 1_500
|
||||
// sys/stat.h SF_DATALESS: the entry's contents live in a file provider, not on disk.
|
||||
const SF_DATALESS = 0x40000000
|
||||
const KNOWN_VOLUME_TYPES: readonly VolumeType[] = [
|
||||
'apfs',
|
||||
'hfs',
|
||||
'smbfs',
|
||||
'nfs',
|
||||
'afpfs',
|
||||
'webdav',
|
||||
'msdos',
|
||||
'exfat'
|
||||
]
|
||||
// Finder's switches for iCloud "Desktop & Documents Folders".
|
||||
const ICLOUD_FINDER_KEY: Partial<Record<MacTccFolderClass, string>> = {
|
||||
desktop: 'FXICloudDriveDesktop',
|
||||
documents: 'FXICloudDriveDocuments'
|
||||
}
|
||||
|
||||
export type TccFolderState = {
|
||||
dataless: FolderFlag
|
||||
icloud: IcloudManaged
|
||||
volumeType: VolumeType
|
||||
}
|
||||
|
||||
type ProbeOutput = { code: number | null; timedOut: boolean; stdout: string; stderr: string }
|
||||
|
||||
export function classifyStatFlags(output: ProbeOutput | null): FolderFlag {
|
||||
if (!output || output.timedOut || output.code !== 0) {
|
||||
return 'unknown'
|
||||
}
|
||||
const flags = Number.parseInt(output.stdout.trim(), 16)
|
||||
if (!Number.isFinite(flags)) {
|
||||
return 'unknown'
|
||||
}
|
||||
return (flags & SF_DATALESS) !== 0 ? 'yes' : 'no'
|
||||
}
|
||||
|
||||
export function classifyIcloudSetting(output: ProbeOutput | null): IcloudManaged {
|
||||
if (!output || output.timedOut) {
|
||||
return 'unknown'
|
||||
}
|
||||
if (output.code === 0) {
|
||||
const value = output.stdout.trim()
|
||||
return value === '1' ? 'yes' : value === '0' ? 'no' : 'unknown'
|
||||
}
|
||||
// A key that was never written means the user never turned the sync on.
|
||||
return /does not exist/.test(output.stderr) ? 'no' : 'unknown'
|
||||
}
|
||||
|
||||
/** Volume type of the longest mount point containing `path`, from `/sbin/mount` output. */
|
||||
export function classifyVolumeType(output: ProbeOutput | null, path: string): VolumeType {
|
||||
if (!output || output.timedOut || output.code !== 0) {
|
||||
return 'unknown'
|
||||
}
|
||||
let best: { mountPoint: string; type: string } | null = null
|
||||
for (const line of output.stdout.split('\n')) {
|
||||
const match = / on (.+) \(([^,)]+)/.exec(line)
|
||||
if (!match) {
|
||||
continue
|
||||
}
|
||||
const [, mountPoint, type] = match
|
||||
const contains = mountPoint === '/' || path === mountPoint || path.startsWith(`${mountPoint}/`)
|
||||
if (contains && (!best || mountPoint.length > best.mountPoint.length)) {
|
||||
best = { mountPoint, type }
|
||||
}
|
||||
}
|
||||
if (!best) {
|
||||
return 'unknown'
|
||||
}
|
||||
return KNOWN_VOLUME_TYPES.find((type) => type === best.type) ?? 'other'
|
||||
}
|
||||
|
||||
async function probe(
|
||||
program: string,
|
||||
args: string[],
|
||||
run: typeof runProcess
|
||||
): Promise<ProbeOutput | null> {
|
||||
try {
|
||||
return await run({
|
||||
program,
|
||||
args,
|
||||
timeoutMs: PROBE_TIMEOUT_MS,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
killOnOutputLimit: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** A root relocated to a hung volume must not hold the denial notice behind it. */
|
||||
async function resolveWithin(path: string, timeoutMs: number): Promise<string> {
|
||||
let timer: NodeJS.Timeout | undefined
|
||||
const deadline = new Promise<string>((resolve) => {
|
||||
timer = setTimeout(() => resolve(path), timeoutMs)
|
||||
timer.unref?.()
|
||||
})
|
||||
try {
|
||||
return await Promise.race([realpath(path).catch(() => path), deadline])
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/** Metadata of the class root only: none of these read the protected folder's contents. */
|
||||
export async function readTccFolderState(
|
||||
classRoot: string,
|
||||
cwdClass: MacTccFolderClass,
|
||||
run: typeof runProcess
|
||||
): Promise<TccFolderState> {
|
||||
// A relocated class root (symlink to another volume) is what decides the volume.
|
||||
const resolved = await resolveWithin(classRoot, PROBE_TIMEOUT_MS)
|
||||
const icloudKey = ICLOUD_FINDER_KEY[cwdClass]
|
||||
const [flags, icloud, mounts] = await Promise.all([
|
||||
probe('/usr/bin/stat', ['-f', '%Xf', resolved], run),
|
||||
icloudKey ? probe('/usr/bin/defaults', ['read', 'com.apple.finder', icloudKey], run) : null,
|
||||
probe('/sbin/mount', [], run)
|
||||
])
|
||||
return {
|
||||
dataless: classifyStatFlags(flags),
|
||||
icloud: icloudKey ? classifyIcloudSetting(icloud) : 'not_applicable',
|
||||
volumeType: classifyVolumeType(mounts, resolved)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// macOS's own record of a terminal-host folder denial: tccd decisions and kernel sandbox denies.
|
||||
|
||||
import type { runProcess } from '@orca/process-host'
|
||||
import { z } from 'zod'
|
||||
import type { MacTccFolderClass } from '../../../shared/daemon-adoption-telemetry'
|
||||
import type {
|
||||
TccAsked,
|
||||
TccAuthReason,
|
||||
TccAuthValue,
|
||||
TccLogAccess,
|
||||
RequirementFailure,
|
||||
TccService,
|
||||
YesNo
|
||||
} from '../../../shared/daemon-tcc-denial-capture'
|
||||
import { TCC_AUTH_REASONS } from '../../../shared/daemon-tcc-denial-capture'
|
||||
|
||||
// A prompted request logs its attribution long before its result; 30 s keeps both in one window.
|
||||
const LOG_LOOKBACK_MS = 30_000
|
||||
// End near the denial so later requests of the same class cannot replace its verdict.
|
||||
const LOG_LOOKAHEAD_MS = 2_000
|
||||
const LOG_TIMEOUT_MS = 5_000
|
||||
const LOG_MAX_OUTPUT_BYTES = 8 * 1024 * 1024
|
||||
const LOG_PREDICATE = '(subsystem == "com.apple.TCC") OR (sender == "Sandbox")'
|
||||
|
||||
export type TccLogVerdict = {
|
||||
logAccess: TccLogAccess
|
||||
tccdAsked: TccAsked
|
||||
authValue: TccAuthValue
|
||||
authReason: TccAuthReason
|
||||
service: TccService
|
||||
requirementFailure: RequirementFailure
|
||||
kernelDeny: YesNo
|
||||
}
|
||||
|
||||
export type TccLogSubject = {
|
||||
helperPid: number
|
||||
/** Helper executable path; tccd names it in attribution lines. */
|
||||
helperPath: string | null
|
||||
/** Code identifier tccd reports for both the app and its helper. */
|
||||
appId: string
|
||||
cwdClass: MacTccFolderClass
|
||||
}
|
||||
|
||||
type LogRecord = { message: string; msgId: string | null }
|
||||
|
||||
type MsgGroup = {
|
||||
relevant: boolean
|
||||
service: string | null
|
||||
result: { authValue: string; authReason: string } | null
|
||||
}
|
||||
|
||||
const LOG_ENTRY_SCHEMA = z.object({
|
||||
eventMessage: z.string()
|
||||
})
|
||||
const MSG_ID_PATTERN = /\bmsgID=(\d+\.\d+)/
|
||||
const ANY_PID_PATTERN = /\bpid=\d+/
|
||||
const SERVICE_PATTERN = /\bservice=kTCCService(\w+)/
|
||||
const RESULT_PATTERN = /AUTHREQ_RESULT: .*\bauthValue=(\d+), authReason=(\d+)/
|
||||
const REQUIREMENT_FAILURE_PATTERN = /failed to match existing code requirement/i
|
||||
const STATIC_REQUIREMENT_CHECK_PATTERN =
|
||||
/matchesCodeRequirement:\]: .* from (.+?) : (.+); status: (-?\d+)/
|
||||
|
||||
const SERVICE_BY_NAME: Record<string, TccService> = {
|
||||
SystemPolicyDocumentsFolder: 'documents',
|
||||
SystemPolicyDesktopFolder: 'desktop',
|
||||
SystemPolicyDownloadsFolder: 'downloads',
|
||||
SystemPolicyAllFiles: 'all_files'
|
||||
}
|
||||
|
||||
const AUTH_VALUE_BY_NUMBER: Record<string, TccAuthValue> = {
|
||||
'0': 'denied',
|
||||
'1': 'unknown',
|
||||
'2': 'allowed',
|
||||
'3': 'limited'
|
||||
}
|
||||
|
||||
function toRecord(rawLine: string): LogRecord | null {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawLine)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const entry = LOG_ENTRY_SCHEMA.safeParse(parsed)
|
||||
if (!entry.success) {
|
||||
return null
|
||||
}
|
||||
const message = entry.data.eventMessage
|
||||
return { message, msgId: MSG_ID_PATTERN.exec(message)?.[1] ?? null }
|
||||
}
|
||||
|
||||
/** A failed requirement check for this code identity; the app and its hosts share it. */
|
||||
function isIdentityRequirementFailure(message: string, subject: TccLogSubject): boolean {
|
||||
if (REQUIREMENT_FAILURE_PATTERN.test(message)) {
|
||||
return (
|
||||
new RegExp(`\\bsubject ${subject.appId.replace(/\./g, '\\.')}\\b`).test(message) ||
|
||||
(!!subject.helperPath && message.includes(subject.helperPath))
|
||||
)
|
||||
}
|
||||
// tccd also checks "anchor apple" on every client; only a failed stored requirement counts.
|
||||
const check = STATIC_REQUIREMENT_CHECK_PATTERN.exec(message)
|
||||
return (
|
||||
!!check &&
|
||||
(check[1] === subject.appId || check[1] === subject.helperPath) &&
|
||||
check[2].trim() !== 'anchor apple' &&
|
||||
check[3] !== '0'
|
||||
)
|
||||
}
|
||||
|
||||
function authReasonOf(raw: string | undefined): TccAuthReason {
|
||||
if (raw === undefined) {
|
||||
return 'none'
|
||||
}
|
||||
return TCC_AUTH_REASONS.find((reason) => reason === raw) ?? 'other'
|
||||
}
|
||||
|
||||
/** Derive enums from lines about the helper; raw `log show --style ndjson` text is never kept. */
|
||||
export function parseTccLogVerdict(
|
||||
stdout: string,
|
||||
subject: TccLogSubject,
|
||||
logAccess: TccLogAccess
|
||||
): TccLogVerdict {
|
||||
const pidPattern = new RegExp(`\\bpid=${subject.helperPid}\\b`)
|
||||
const pathNeedles = subject.helperPath ? [subject.helperPath, encodeURI(subject.helperPath)] : []
|
||||
// An earlier incarnation of the same copy shares the path, so an explicit pid outranks it.
|
||||
const namesHelper = (message: string): boolean =>
|
||||
pidPattern.test(message) ||
|
||||
(!ANY_PID_PATTERN.test(message) && pathNeedles.some((needle) => message.includes(needle)))
|
||||
// Sandbox coalesces repeats as "N duplicate reports for Sandbox: …"; folder denies add "System Policy:".
|
||||
const sandboxDeny = new RegExp(
|
||||
`Sandbox: [^\\n]*?\\(${subject.helperPid}\\) (?:System Policy: )?deny\\(`
|
||||
)
|
||||
|
||||
const records = stdout
|
||||
.split('\n')
|
||||
.map(toRecord)
|
||||
.filter((record): record is LogRecord => record !== null)
|
||||
const groups = new Map<string, MsgGroup>()
|
||||
for (const record of records) {
|
||||
if (!record.msgId) {
|
||||
continue
|
||||
}
|
||||
const group = groups.get(record.msgId) ?? { relevant: false, service: null, result: null }
|
||||
groups.set(record.msgId, group)
|
||||
group.relevant ||= namesHelper(record.message)
|
||||
group.service ??= SERVICE_PATTERN.exec(record.message)?.[1] ?? null
|
||||
const result = RESULT_PATTERN.exec(record.message)
|
||||
if (result) {
|
||||
group.result = { authValue: result[1], authReason: result[2] }
|
||||
}
|
||||
}
|
||||
|
||||
let kernelDeny = false
|
||||
let requirementFailure: RequirementFailure = 'no'
|
||||
for (const record of records) {
|
||||
const inRelevantGroup = record.msgId !== null && groups.get(record.msgId)?.relevant === true
|
||||
const deny = sandboxDeny.test(record.message)
|
||||
const helperRecord = inRelevantGroup || namesHelper(record.message)
|
||||
const requirement = isIdentityRequirementFailure(record.message, subject)
|
||||
if (!helperRecord && !deny && !requirement) {
|
||||
continue
|
||||
}
|
||||
kernelDeny ||= deny
|
||||
if (requirement) {
|
||||
// Identifier-only evidence may be the app's or another host's check, so it is not blamed here.
|
||||
requirementFailure = helperRecord
|
||||
? 'yes'
|
||||
: requirementFailure === 'yes'
|
||||
? 'yes'
|
||||
: 'uncorrelated'
|
||||
}
|
||||
}
|
||||
|
||||
const relevantGroups = [...groups.values()].filter((group) => group.relevant)
|
||||
const decided = relevantGroups.filter((group) => group.result !== null)
|
||||
// Overlapping requests can resolve out of order; a later "allowed" must not mask a denial.
|
||||
const denied = decided.filter((group) => group.result?.authValue === '0')
|
||||
const chosen =
|
||||
denied.findLast(
|
||||
(group) => group.service !== null && SERVICE_BY_NAME[group.service] === subject.cwdClass
|
||||
) ??
|
||||
decided.findLast(
|
||||
(group) => group.service !== null && SERVICE_BY_NAME[group.service] === subject.cwdClass
|
||||
) ??
|
||||
decided.at(-1) ??
|
||||
relevantGroups.at(-1)
|
||||
const serviceName = chosen?.service ?? null
|
||||
|
||||
return {
|
||||
logAccess,
|
||||
// "no" means no request tied to this helper in the window, and only from a complete read.
|
||||
tccdAsked: relevantGroups.length > 0 ? 'yes' : logAccess === 'ok' ? 'no' : 'unknown',
|
||||
authValue: chosen?.result ? (AUTH_VALUE_BY_NUMBER[chosen.result.authValue] ?? 'other') : 'none',
|
||||
authReason: authReasonOf(chosen?.result?.authReason),
|
||||
service: serviceName === null ? 'none' : (SERVICE_BY_NAME[serviceName] ?? 'other'),
|
||||
requirementFailure,
|
||||
kernelDeny: kernelDeny ? 'yes' : 'no'
|
||||
}
|
||||
}
|
||||
|
||||
function formatLogTime(atMs: number): string {
|
||||
// `log show --start/--end` accept "YYYY-MM-DD HH:MM:SS+ZZZZ".
|
||||
const iso = new Date(atMs).toISOString()
|
||||
return `${iso.slice(0, 10)} ${iso.slice(11, 19)}+0000`
|
||||
}
|
||||
|
||||
function classifyLogFailure(output: string): TccLogAccess {
|
||||
return /must be admin|not permitted|permission denied/i.test(output) ? 'denied' : 'error'
|
||||
}
|
||||
|
||||
/** Bounded `log show` around the denial; never throws. */
|
||||
export async function readTccLogVerdict(
|
||||
denialAtMs: number,
|
||||
subject: TccLogSubject,
|
||||
run: typeof runProcess
|
||||
): Promise<TccLogVerdict> {
|
||||
let logAccess: TccLogAccess
|
||||
let stdout = ''
|
||||
try {
|
||||
const result = await run({
|
||||
program: '/usr/bin/log',
|
||||
args: [
|
||||
'show',
|
||||
// Requirement checks (matchesCodeRequirement) are Info records.
|
||||
'--info',
|
||||
'--style',
|
||||
'ndjson',
|
||||
'--start',
|
||||
formatLogTime(denialAtMs - LOG_LOOKBACK_MS),
|
||||
'--end',
|
||||
formatLogTime(denialAtMs + LOG_LOOKAHEAD_MS),
|
||||
'--predicate',
|
||||
LOG_PREDICATE
|
||||
],
|
||||
timeoutMs: LOG_TIMEOUT_MS,
|
||||
maxOutputBytes: LOG_MAX_OUTPUT_BYTES,
|
||||
killOnOutputLimit: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
stdout = result.stdout
|
||||
logAccess = result.timedOut
|
||||
? 'timeout'
|
||||
: result.outputTruncated
|
||||
? 'truncated'
|
||||
: result.code === 0
|
||||
? 'ok'
|
||||
: classifyLogFailure(`${result.stderr}\n${result.stdout}`)
|
||||
} catch {
|
||||
logAccess = 'error'
|
||||
}
|
||||
// A killed `log show` still printed complete lines before its deadline.
|
||||
return parseTccLogVerdict(stdout, subject, logAccess)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Whether the live helper and its on-disk copy still carry the app's signature at a denial.
|
||||
|
||||
import type { runProcess } from '@orca/process-host'
|
||||
import type { SignatureCheck } from '../../../shared/daemon-tcc-denial-capture'
|
||||
|
||||
const CODESIGN = '/usr/bin/codesign'
|
||||
const CODESIGN_TIMEOUT_MS = 5_000
|
||||
const CODESIGN_MAX_OUTPUT_BYTES = 64 * 1024
|
||||
|
||||
export type HelperSignatureChecks = {
|
||||
live: SignatureCheck
|
||||
diskCopy: SignatureCheck
|
||||
}
|
||||
|
||||
type CodesignRun = { code: number | null; timedOut: boolean; output: string } | null
|
||||
|
||||
/** `…/X.app/Contents/MacOS/x` → `…/X.app`; null when the path is not inside a bundle. */
|
||||
export function bundlePathOf(executablePath: string | null): string | null {
|
||||
if (!executablePath) {
|
||||
return null
|
||||
}
|
||||
const index = executablePath.lastIndexOf('.app/Contents/')
|
||||
return index === -1 ? null : executablePath.slice(0, index + '.app'.length)
|
||||
}
|
||||
|
||||
/** codesign exits 1 on a failed verify and 3 on an unmet requirement; a vanished pid proves nothing. */
|
||||
export function classifyCodesignVerify(run: CodesignRun): SignatureCheck {
|
||||
if (
|
||||
!run ||
|
||||
run.timedOut ||
|
||||
/no guest with the requested attributes|No such process/i.test(run.output)
|
||||
) {
|
||||
return 'error'
|
||||
}
|
||||
if (run.code === 0) {
|
||||
return 'pass'
|
||||
}
|
||||
return run.code === 1 || run.code === 3 ? 'fail' : 'error'
|
||||
}
|
||||
|
||||
export function designatedRequirementOf(run: CodesignRun): string | null {
|
||||
if (!run || run.timedOut || run.code !== 0) {
|
||||
return null
|
||||
}
|
||||
return /designated => (.+)/.exec(run.output)?.[1]?.trim() ?? null
|
||||
}
|
||||
|
||||
async function codesign(args: string[], run: typeof runProcess): Promise<CodesignRun> {
|
||||
try {
|
||||
const result = await run({
|
||||
program: CODESIGN,
|
||||
args,
|
||||
timeoutMs: CODESIGN_TIMEOUT_MS,
|
||||
maxOutputBytes: CODESIGN_MAX_OUTPUT_BYTES,
|
||||
killOnOutputLimit: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
return {
|
||||
code: result.code,
|
||||
timedOut: result.timedOut,
|
||||
output: `${result.stderr}\n${result.stdout}`
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
let appRequirement: Promise<string | null> | null = null
|
||||
|
||||
/** The running app's designated requirement; read once per app process. */
|
||||
function appDesignatedRequirement(run: typeof runProcess): Promise<string | null> {
|
||||
const appBundle = bundlePathOf(process.execPath)
|
||||
if (!appBundle) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
appRequirement ??= codesign(['--display', '-r-', appBundle], run).then((result) => {
|
||||
const requirement = designatedRequirementOf(result)
|
||||
// Retry a failed read at the next denial instead of pinning the failure.
|
||||
if (requirement === null) {
|
||||
appRequirement = null
|
||||
}
|
||||
return requirement
|
||||
})
|
||||
return appRequirement
|
||||
}
|
||||
|
||||
// `codesign --verify -R … +pid` fails with EINVAL whenever the requirement matches (macOS 27), so
|
||||
// verify the live code dynamically and compare its designated requirement with the app's instead.
|
||||
async function checkLiveHelper(helperPid: number, run: typeof runProcess): Promise<SignatureCheck> {
|
||||
const [verify, liveDisplay, expected] = await Promise.all([
|
||||
codesign(['--verify', '--strict', `+${helperPid}`], run),
|
||||
codesign(['--display', '-r-', `+${helperPid}`], run),
|
||||
appDesignatedRequirement(run)
|
||||
])
|
||||
const verdict = classifyCodesignVerify(verify)
|
||||
if (verdict !== 'pass') {
|
||||
return verdict
|
||||
}
|
||||
const live = designatedRequirementOf(liveDisplay)
|
||||
if (!live || !expected) {
|
||||
return 'error'
|
||||
}
|
||||
return live === expected ? 'pass' : 'fail'
|
||||
}
|
||||
|
||||
export async function checkHelperSignatures(
|
||||
helperPid: number,
|
||||
helperExecutablePath: string | null,
|
||||
run: typeof runProcess
|
||||
): Promise<HelperSignatureChecks> {
|
||||
const helperBundle = bundlePathOf(helperExecutablePath)
|
||||
const [live, diskCopy] = await Promise.all([
|
||||
checkLiveHelper(helperPid, run),
|
||||
helperBundle
|
||||
? codesign(['--verify', '--strict', helperBundle], run).then(classifyCodesignVerify)
|
||||
: Promise.resolve<SignatureCheck>('error')
|
||||
])
|
||||
return { live, diskCopy }
|
||||
}
|
||||
|
||||
export function resetHelperSignatureChecksForTests(): void {
|
||||
appRequirement = null
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
track: vi.fn(),
|
||||
telemetryEnabled: vi.fn(),
|
||||
logVerdict: vi.fn(),
|
||||
signatures: vi.fn(),
|
||||
fullDiskAccess: vi.fn(),
|
||||
codeIdentity: vi.fn(),
|
||||
runProcess: vi.fn()
|
||||
}))
|
||||
const trackMock = mocks.track
|
||||
const telemetryEnabledMock = mocks.telemetryEnabled
|
||||
const logVerdictMock = mocks.logVerdict
|
||||
vi.mock('@orca/process-host', () => ({ runProcess: mocks.runProcess }))
|
||||
vi.mock('../../../telemetry/client', () => ({
|
||||
track: mocks.track,
|
||||
isTelemetryEnabled: mocks.telemetryEnabled
|
||||
}))
|
||||
vi.mock('../tcc-denial-log-verdict', () => ({ readTccLogVerdict: mocks.logVerdict }))
|
||||
vi.mock('../tcc-denial-signature-checks', () => ({ checkHelperSignatures: mocks.signatures }))
|
||||
vi.mock('../daemon-full-disk-access-status', () => ({
|
||||
getTerminalHostsFullDiskAccessStatus: mocks.fullDiskAccess
|
||||
}))
|
||||
vi.mock('../../executable-host/macos/daemon-mac-code-identity', () => ({
|
||||
inspectMacProcessCodeIdentity: mocks.codeIdentity
|
||||
}))
|
||||
|
||||
import type { DaemonEndpointIdentity } from '../../protocol/daemon-hello-protocol'
|
||||
import type { readTccFolderState } from '../tcc-denial-folder-state'
|
||||
import {
|
||||
noteHelperFolderReadable,
|
||||
prepareTccDenialCapture,
|
||||
releaseTccDenialCapture,
|
||||
resetTccDenialCaptureForTests,
|
||||
runTccDenialCapture
|
||||
} from '../tcc-denial-capture'
|
||||
|
||||
const HELPER: DaemonEndpointIdentity = { pid: 1206, startedAtMs: 1_000, launchNonce: 'n1' }
|
||||
const FOLDER = async () => ({ dataless: 'yes', icloud: 'yes', volumeType: 'apfs' }) as const
|
||||
|
||||
beforeEach(() => {
|
||||
resetTccDenialCaptureForTests()
|
||||
trackMock.mockReset()
|
||||
telemetryEnabledMock.mockReset().mockReturnValue(true)
|
||||
mocks.signatures.mockReset().mockResolvedValue({ live: 'pass', diskCopy: 'fail' })
|
||||
mocks.fullDiskAccess.mockReset().mockResolvedValue('denied')
|
||||
mocks.codeIdentity.mockReset().mockResolvedValue({ identity: 'resolved', executablePath: null })
|
||||
mocks.runProcess.mockReset().mockResolvedValue({
|
||||
code: 0,
|
||||
signal: null,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
timedOut: false
|
||||
})
|
||||
logVerdictMock.mockReset().mockResolvedValue({
|
||||
logAccess: 'ok',
|
||||
tccdAsked: 'no',
|
||||
authValue: 'none',
|
||||
authReason: 'none',
|
||||
service: 'none',
|
||||
requirementFailure: 'no',
|
||||
kernelDeny: 'yes'
|
||||
})
|
||||
})
|
||||
|
||||
describe('tcc denial capture', () => {
|
||||
it('runs no probe or log read for a user who opted out of telemetry', async () => {
|
||||
telemetryEnabledMock.mockReturnValue(false)
|
||||
const readFolder = vi.fn(FOLDER)
|
||||
expect(await prepareTccDenialCapture(HELPER, 'documents', 5_000, readFolder)).toBeNull()
|
||||
expect(readFolder).not.toHaveBeenCalled()
|
||||
|
||||
// Opting out while the app-side read waits stops the capture before the log is read.
|
||||
telemetryEnabledMock.mockReturnValue(true)
|
||||
const start = (await prepareTccDenialCapture(HELPER, 'documents', 5_000, FOLDER))!
|
||||
telemetryEnabledMock.mockReturnValue(false)
|
||||
await runTccDenialCapture(start)
|
||||
expect(logVerdictMock).not.toHaveBeenCalled()
|
||||
expect(trackMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// Opt out while each stage is in flight: nothing after it may start, and the claim is freed.
|
||||
it.each([
|
||||
{
|
||||
stage: 'identity probe',
|
||||
probe: mocks.codeIdentity,
|
||||
result: { identity: 'resolved', executablePath: null },
|
||||
skipped: [mocks.logVerdict, mocks.signatures, mocks.fullDiskAccess]
|
||||
},
|
||||
{
|
||||
// The access reader is lazily imported, so it starts after an await of its own.
|
||||
stage: 'log reader, before the lazily imported access reader',
|
||||
probe: mocks.logVerdict,
|
||||
result: {
|
||||
logAccess: 'ok',
|
||||
tccdAsked: 'no',
|
||||
authValue: 'none',
|
||||
authReason: 'none',
|
||||
service: 'none',
|
||||
requirementFailure: 'no',
|
||||
kernelDeny: 'no'
|
||||
},
|
||||
skipped: [mocks.fullDiskAccess]
|
||||
},
|
||||
{
|
||||
stage: 'log, signature and access probes',
|
||||
probe: mocks.signatures,
|
||||
result: { live: 'pass', diskCopy: 'pass' },
|
||||
skipped: []
|
||||
}
|
||||
])('stops after the $stage when telemetry is turned off', async ({ probe, result, skipped }) => {
|
||||
const start = (await prepareTccDenialCapture(HELPER, 'documents', 5_000, FOLDER))!
|
||||
probe.mockImplementationOnce(async () => {
|
||||
telemetryEnabledMock.mockReturnValue(false)
|
||||
return result
|
||||
})
|
||||
await runTccDenialCapture(start)
|
||||
|
||||
for (const probe of skipped) {
|
||||
expect(probe).not.toHaveBeenCalled()
|
||||
}
|
||||
expect(trackMock).not.toHaveBeenCalled()
|
||||
telemetryEnabledMock.mockReturnValue(true)
|
||||
expect(await prepareTccDenialCapture(HELPER, 'documents', 6_000, FOLDER)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('stops after the folder probes when telemetry is turned off', async () => {
|
||||
const readFolder = vi.fn(async () => {
|
||||
telemetryEnabledMock.mockReturnValue(false)
|
||||
return FOLDER()
|
||||
})
|
||||
expect(await prepareTccDenialCapture(HELPER, 'documents', 5_000, readFolder)).toBeNull()
|
||||
telemetryEnabledMock.mockReturnValue(true)
|
||||
expect(await prepareTccDenialCapture(HELPER, 'documents', 6_000, FOLDER)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('hands every probe a runner that refuses to spawn once telemetry is off', async () => {
|
||||
const readFolder = vi.fn<typeof readTccFolderState>(FOLDER)
|
||||
await prepareTccDenialCapture(HELPER, 'documents', 5_000, readFolder)
|
||||
const runner = readFolder.mock.calls[0][2]
|
||||
|
||||
await runner({ program: '/usr/bin/true' })
|
||||
telemetryEnabledMock.mockReturnValue(false)
|
||||
await expect(runner({ program: '/usr/bin/true' })).rejects.toThrow('telemetry is off')
|
||||
expect(mocks.runProcess).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('captures once per helper incarnation and folder class', async () => {
|
||||
const start = await prepareTccDenialCapture(HELPER, 'documents', 5_000, FOLDER)
|
||||
expect(start).not.toBeNull()
|
||||
await runTccDenialCapture(start!)
|
||||
await runTccDenialCapture(start!)
|
||||
|
||||
expect(trackMock).toHaveBeenCalledTimes(1)
|
||||
expect(await prepareTccDenialCapture(HELPER, 'documents', 6_000, FOLDER)).toBeNull()
|
||||
expect(await prepareTccDenialCapture(HELPER, 'desktop', 6_000, FOLDER)).not.toBeNull()
|
||||
expect(
|
||||
await prepareTccDenialCapture({ ...HELPER, launchNonce: 'n2' }, 'documents', 6_000, FOLDER)
|
||||
).not.toBeNull()
|
||||
})
|
||||
|
||||
it('probes the folder once for concurrent denials, and again only after a release', async () => {
|
||||
const readFolder = vi.fn(FOLDER)
|
||||
const starts = await Promise.all(
|
||||
Array.from({ length: 5 }, () =>
|
||||
prepareTccDenialCapture(HELPER, 'documents', 5_000, readFolder)
|
||||
)
|
||||
)
|
||||
expect(readFolder).toHaveBeenCalledTimes(1)
|
||||
expect(starts.filter((start) => start !== null)).toHaveLength(1)
|
||||
|
||||
releaseTccDenialCapture(starts.find((start) => start !== null)!)
|
||||
expect(await prepareTccDenialCapture(HELPER, 'documents', 6_000, readFolder)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('sends enums only, with earlier good reads of the same class on this helper', async () => {
|
||||
noteHelperFolderReadable(HELPER, 'documents', 2_000)
|
||||
noteHelperFolderReadable(HELPER, 'documents', 3_000)
|
||||
noteHelperFolderReadable(HELPER, 'desktop', 4_500)
|
||||
|
||||
await runTccDenialCapture((await prepareTccDenialCapture(HELPER, 'documents', 65_000, FOLDER))!)
|
||||
|
||||
expect(trackMock).toHaveBeenCalledWith(
|
||||
'daemon_pty_cwd_denial_capture',
|
||||
expect.objectContaining({
|
||||
cwd_class: 'documents',
|
||||
kernel_deny: 'yes',
|
||||
live_signature: 'pass',
|
||||
disk_copy_signature: 'fail',
|
||||
helper_age_bucket: '1-10m',
|
||||
helper_origin: 'adopted',
|
||||
good_reads_bucket: '2-5',
|
||||
since_good_read_bucket: '1-5m',
|
||||
full_disk_access: 'denied',
|
||||
fork_fallback: 'unknown',
|
||||
folder_dataless: 'yes',
|
||||
folder_icloud: 'yes',
|
||||
volume_type: 'apfs'
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('swallows a failing probe and does not retry the same helper and class', async () => {
|
||||
logVerdictMock.mockRejectedValue(new Error('log exploded'))
|
||||
const start = (await prepareTccDenialCapture(HELPER, 'downloads', 5_000, FOLDER))!
|
||||
|
||||
await expect(runTccDenialCapture(start)).resolves.toBeUndefined()
|
||||
expect(trackMock).not.toHaveBeenCalled()
|
||||
expect(await prepareTccDenialCapture(HELPER, 'downloads', 6_000, FOLDER)).toBeNull()
|
||||
})
|
||||
|
||||
it('still captures when the folder state cannot be read', async () => {
|
||||
const start = await prepareTccDenialCapture(HELPER, 'desktop', 5_000, async () => {
|
||||
throw new Error('stat failed')
|
||||
})
|
||||
expect(start?.folderState).toEqual({
|
||||
dataless: 'unknown',
|
||||
icloud: 'unknown',
|
||||
volumeType: 'unknown'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
classifyIcloudSetting,
|
||||
classifyStatFlags,
|
||||
classifyVolumeType
|
||||
} from '../tcc-denial-folder-state'
|
||||
|
||||
function ok(stdout: string, code = 0, stderr = '') {
|
||||
return { code, timedOut: false, stdout, stderr }
|
||||
}
|
||||
|
||||
describe('folder state enums', () => {
|
||||
it('reads SF_DATALESS from `stat -f %Xf`', () => {
|
||||
expect(classifyStatFlags(ok('40000000\n'))).toBe('yes')
|
||||
expect(classifyStatFlags(ok('40000040\n'))).toBe('yes')
|
||||
expect(classifyStatFlags(ok('0\n'))).toBe('no')
|
||||
expect(classifyStatFlags(ok('', 1))).toBe('unknown')
|
||||
})
|
||||
|
||||
it('treats a never-written Finder key as iCloud off', () => {
|
||||
expect(classifyIcloudSetting(ok('1\n'))).toBe('yes')
|
||||
expect(classifyIcloudSetting(ok('0\n'))).toBe('no')
|
||||
expect(
|
||||
classifyIcloudSetting(
|
||||
ok(
|
||||
'',
|
||||
1,
|
||||
'The domain/default pair of (com.apple.finder, FXICloudDriveDesktop) does not exist'
|
||||
)
|
||||
)
|
||||
).toBe('no')
|
||||
expect(classifyIcloudSetting({ ...ok(''), timedOut: true })).toBe('unknown')
|
||||
})
|
||||
|
||||
it('picks the longest mount point that contains the folder', () => {
|
||||
const mounts = ok(
|
||||
[
|
||||
'/dev/disk3s1s1 on / (apfs, sealed, local, read-only, journaled)',
|
||||
'/dev/disk3s5 on /System/Volumes/Data (apfs, local, journaled, nobrowse, protect, root data)',
|
||||
'//user@nas/home on /Volumes/home (smbfs, nodev, nosuid, mounted by user)',
|
||||
'/dev/disk5s1 on /Volumes/home backup (exfat, local, nodev, nosuid, noowners)'
|
||||
].join('\n')
|
||||
)
|
||||
expect(classifyVolumeType(mounts, '/Volumes/home/Documents')).toBe('smbfs')
|
||||
expect(classifyVolumeType(mounts, '/Volumes/home backup/Documents')).toBe('exfat')
|
||||
expect(classifyVolumeType(mounts, '/Users/user/Documents')).toBe('apfs')
|
||||
expect(
|
||||
classifyVolumeType(ok('map auto_home on /System/Volumes/Data/home (autofs)'), '/x')
|
||||
).toBe('unknown')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,280 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { runProcess } from '@orca/process-host'
|
||||
import { parseTccLogVerdict, readTccLogVerdict } from '../tcc-denial-log-verdict'
|
||||
|
||||
// Real tccd lines from a macOS 27.2 VM (usernames redacted), as `log show --style ndjson` emits them.
|
||||
const HELPER =
|
||||
'/Users/user/Library/Application Support/orca/daemon-host/macos/terminal-host-57202dec6187e819396a5a0ab07c2932bf5a00fe/app.noindex/Orca Terminal Host.app/Contents/MacOS/orca-terminal-host'
|
||||
const TCCD = '/System/Library/PrivateFrameworks/TCC.framework/Support/tccd'
|
||||
const SANDBOXD = '/usr/libexec/sandboxd'
|
||||
const DENIED_AT_MS = Date.UTC(2026, 10, 13, 20, 24, 30)
|
||||
|
||||
function line(timestamp: string, image: string, pid: number, eventMessage: string): string {
|
||||
return JSON.stringify({
|
||||
timestamp: `2026-11-13 ${timestamp}+0000`,
|
||||
processImagePath: image,
|
||||
processID: pid,
|
||||
subsystem: 'com.apple.TCC',
|
||||
eventMessage
|
||||
})
|
||||
}
|
||||
|
||||
const HELPER_DOWNLOADS_REFUSED = [
|
||||
line(
|
||||
'20:24:20.457760',
|
||||
SANDBOXD,
|
||||
153,
|
||||
'SEND: 0/7 synchronous to com.apple.tccd: request: msgID=153.1126, function=TCCAccessRequest, service=kTCCServiceSystemPolicyDownloadsFolder,'
|
||||
),
|
||||
line(
|
||||
'20:24:20.458006',
|
||||
TCCD,
|
||||
350,
|
||||
'AUTHREQ_CTX: msgID=153.1126, function=TCCAccessRequest, service=kTCCServiceSystemPolicyDownloadsFolder, preflight=no, query=1, client_dict=(null), daemon_dict=<private>'
|
||||
),
|
||||
line(
|
||||
'20:24:20.458018',
|
||||
TCCD,
|
||||
350,
|
||||
`AUTHREQ_ATTRIBUTION: msgID=153.1126, attribution={accessing={TCCDProcess: identifier=com.stablyai.orca, pid=1206, auid=501, euid=501, binary_path=${HELPER}}, requesting={TCCDProcess: identifier=com.apple.sandboxd, pid=153, auid=0, euid=0, binary_path=/usr/libexec/sandboxd}, },`
|
||||
),
|
||||
line(
|
||||
'20:24:49.917729',
|
||||
TCCD,
|
||||
350,
|
||||
'AUTHREQ_RESULT: msgID=153.1126, authValue=0, authReason=2, authVersion=1, desired_auth=0, error=(null),'
|
||||
)
|
||||
]
|
||||
|
||||
// The main app's own refusal: same identifier, different pid; it must not count for the helper.
|
||||
const APP_DOCUMENTS_REFUSED = [
|
||||
line(
|
||||
'20:14:22.730560',
|
||||
TCCD,
|
||||
350,
|
||||
'AUTHREQ_ATTRIBUTION: msgID=153.1044, attribution={responsible={TCCDProcess: identifier=com.stablyai.orca, pid=902, auid=501, euid=501, responsible_path=/Applications/Orca.app/Contents/MacOS/Orca, binary_path=/Applications/Orca.app/Contents/MacOS/Orca}, accessing={TCCDProcess: identifier=com.stablyai.orca.helper, pid=1959, auid=501, euid=501, binary_path=/Applications/Orca.app/Contents/Frameworks/Orca Helper.app/Contents/MacOS/Orca Helper}, requesting={TCCDProcess: identifier=com.apple.sandboxd, pid=153, auid=0, euid=0, binary_path=/usr/libexec/sandboxd}, },'
|
||||
),
|
||||
line(
|
||||
'20:14:22.738046',
|
||||
TCCD,
|
||||
350,
|
||||
'AUTHREQ_RESULT: msgID=153.1044, authValue=0, authReason=2, authVersion=1, desired_auth=0, error=(null),'
|
||||
)
|
||||
]
|
||||
|
||||
const HELPER_DOCUMENTS_ALLOWED = [
|
||||
line(
|
||||
'20:16:05.882048',
|
||||
SANDBOXD,
|
||||
153,
|
||||
'SEND: 0/7 synchronous to com.apple.tccd: request: msgID=153.1060, function=TCCAccessRequest, service=kTCCServiceSystemPolicyDocumentsFolder,'
|
||||
),
|
||||
line(
|
||||
'20:16:05.882368',
|
||||
TCCD,
|
||||
350,
|
||||
`AUTHREQ_ATTRIBUTION: msgID=153.1060, attribution={accessing={TCCDProcess: identifier=com.stablyai.orca, pid=1206, auid=501, euid=501, binary_path=${HELPER}}, requesting={TCCDProcess: identifier=com.apple.sandboxd, pid=153, auid=0, euid=0, binary_path=/usr/libexec/sandboxd}, },`
|
||||
),
|
||||
line(
|
||||
'20:16:05.891091',
|
||||
TCCD,
|
||||
350,
|
||||
'AUTHREQ_RESULT: msgID=153.1060, authValue=2, authReason=2, authVersion=1, desired_auth=0, error=(null),'
|
||||
)
|
||||
]
|
||||
|
||||
// Kernel sandbox report in the shape macOS 27 prints (seen for other processes on a real Mac).
|
||||
const KERNEL_DENY = JSON.stringify({
|
||||
timestamp: '2026-11-13 20:24:20.457000+0000',
|
||||
processImagePath: '/kernel',
|
||||
processID: 0,
|
||||
subsystem: '',
|
||||
eventMessage:
|
||||
'1 duplicate report for Sandbox: orca-terminal-host(1206) deny(1) file-read-data /Users/user/Downloads'
|
||||
})
|
||||
|
||||
const SUBJECT = {
|
||||
helperPid: 1206,
|
||||
helperPath: HELPER,
|
||||
appId: 'com.stablyai.orca',
|
||||
cwdClass: 'downloads' as const
|
||||
}
|
||||
|
||||
function ndjson(lines: string[]): string {
|
||||
return ['Filtering the log data using "subsystem == \\"com.apple.TCC\\""', ...lines].join('\n')
|
||||
}
|
||||
|
||||
describe('parseTccLogVerdict', () => {
|
||||
it("reads the helper's own refused request and ignores the app's", () => {
|
||||
const verdict = parseTccLogVerdict(
|
||||
ndjson([...APP_DOCUMENTS_REFUSED, ...HELPER_DOWNLOADS_REFUSED, KERNEL_DENY]),
|
||||
SUBJECT,
|
||||
'ok'
|
||||
)
|
||||
|
||||
expect(verdict).toMatchObject({
|
||||
logAccess: 'ok',
|
||||
tccdAsked: 'yes',
|
||||
authValue: 'denied',
|
||||
authReason: '2',
|
||||
service: 'downloads',
|
||||
requirementFailure: 'no',
|
||||
kernelDeny: 'yes'
|
||||
})
|
||||
})
|
||||
|
||||
it('reports no tccd request when only other processes asked', () => {
|
||||
expect(parseTccLogVerdict(ndjson(APP_DOCUMENTS_REFUSED), SUBJECT, 'ok')).toMatchObject({
|
||||
tccdAsked: 'no',
|
||||
authValue: 'none',
|
||||
authReason: 'none',
|
||||
service: 'none',
|
||||
kernelDeny: 'no'
|
||||
})
|
||||
})
|
||||
|
||||
it('prefers the decision for the denied folder class over a later one', () => {
|
||||
const verdict = parseTccLogVerdict(
|
||||
ndjson([...HELPER_DOWNLOADS_REFUSED, ...HELPER_DOCUMENTS_ALLOWED]),
|
||||
SUBJECT,
|
||||
'ok'
|
||||
)
|
||||
expect(verdict).toMatchObject({ service: 'downloads', authValue: 'denied' })
|
||||
|
||||
const documents = parseTccLogVerdict(
|
||||
ndjson([...HELPER_DOWNLOADS_REFUSED, ...HELPER_DOCUMENTS_ALLOWED]),
|
||||
{ ...SUBJECT, cwdClass: 'documents' },
|
||||
'ok'
|
||||
)
|
||||
expect(documents).toMatchObject({ service: 'documents', authValue: 'allowed' })
|
||||
})
|
||||
|
||||
it('keeps a denial that resolves after a later request was allowed', () => {
|
||||
const [send, ctx, attribution, deniedResult] = HELPER_DOWNLOADS_REFUSED
|
||||
const later = [send, ctx, attribution].map((entry) =>
|
||||
entry.replaceAll('msgID=153.1126', 'msgID=153.1127')
|
||||
)
|
||||
const allowedResult = deniedResult
|
||||
.replace('msgID=153.1126', 'msgID=153.1127')
|
||||
.replace('authValue=0', 'authValue=2')
|
||||
// Request 1126 starts first, 1127 is allowed, then 1126 is refused.
|
||||
const verdict = parseTccLogVerdict(
|
||||
ndjson([send, ctx, attribution, ...later, allowedResult, deniedResult]),
|
||||
SUBJECT,
|
||||
'ok'
|
||||
)
|
||||
expect(verdict).toMatchObject({ authValue: 'denied', service: 'downloads' })
|
||||
})
|
||||
|
||||
it('flags a failed stored requirement but not the routine "anchor apple" check', () => {
|
||||
const routine = line(
|
||||
'20:06:45.144194',
|
||||
TCCD,
|
||||
157,
|
||||
'-[TCCDAccessIdentity matchesCodeRequirement:]: SecStaticCodeCheckValidity() static code (0x7cf9194300) from com.stablyai.orca : anchor apple; status: -67050'
|
||||
)
|
||||
expect(parseTccLogVerdict(ndjson([routine]), SUBJECT, 'ok').requirementFailure).toBe('no')
|
||||
|
||||
const failed = line(
|
||||
'20:06:46.000000',
|
||||
TCCD,
|
||||
157,
|
||||
'Failed to match existing code requirement for subject com.stablyai.orca and service kTCCServiceSystemPolicyDownloadsFolder'
|
||||
)
|
||||
// The app and its hosts share the identifier, so this cannot be blamed on this helper.
|
||||
expect(parseTccLogVerdict(ndjson([failed]), SUBJECT, 'ok').requirementFailure).toBe(
|
||||
'uncorrelated'
|
||||
)
|
||||
|
||||
const helperCheck = line(
|
||||
'20:06:47.000000',
|
||||
TCCD,
|
||||
157,
|
||||
`-[TCCDAccessIdentity matchesCodeRequirement:]: SecStaticCodeCheckValidity() static code (0x7cf9194300) from ${HELPER} : identifier "com.stablyai.orca" and anchor apple generic; status: -67050`
|
||||
)
|
||||
expect(
|
||||
parseTccLogVerdict(ndjson([failed, helperCheck]), SUBJECT, 'ok').requirementFailure
|
||||
).toBe('yes')
|
||||
})
|
||||
|
||||
it('ignores requirement failures for other apps', () => {
|
||||
const other = line(
|
||||
'20:06:46.000000',
|
||||
TCCD,
|
||||
157,
|
||||
'Failed to match existing code requirement for subject org.example.other and service kTCCServiceSystemPolicyDownloadsFolder'
|
||||
)
|
||||
expect(parseTccLogVerdict(ndjson([other]), SUBJECT, 'ok')).toMatchObject({
|
||||
requirementFailure: 'no'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not credit an earlier helper on the same copy path to this one', () => {
|
||||
const earlierHelper = HELPER_DOWNLOADS_REFUSED.map((entry) =>
|
||||
entry.replace('pid=1206', 'pid=1100')
|
||||
)
|
||||
expect(parseTccLogVerdict(ndjson(earlierHelper), SUBJECT, 'ok')).toMatchObject({
|
||||
tccdAsked: 'no',
|
||||
authValue: 'none'
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves tccd_asked unknown when the log was unreadable or cut short', () => {
|
||||
expect(parseTccLogVerdict('', SUBJECT, 'denied').tccdAsked).toBe('unknown')
|
||||
expect(parseTccLogVerdict(ndjson(APP_DOCUMENTS_REFUSED), SUBJECT, 'truncated').tccdAsked).toBe(
|
||||
'unknown'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readTccLogVerdict', () => {
|
||||
it('asks for Info records in a window that ends at the denial', async () => {
|
||||
let args: readonly string[] = []
|
||||
await readTccLogVerdict(DENIED_AT_MS, SUBJECT, async (spec) => {
|
||||
args = spec.args ?? []
|
||||
return { code: 0, signal: null, stdout: '', stderr: '', timedOut: false }
|
||||
})
|
||||
expect(args).toEqual([
|
||||
'show',
|
||||
'--info',
|
||||
'--style',
|
||||
'ndjson',
|
||||
'--start',
|
||||
'2026-11-13 20:24:00+0000',
|
||||
'--end',
|
||||
'2026-11-13 20:24:32+0000',
|
||||
'--predicate',
|
||||
'(subsystem == "com.apple.TCC") OR (sender == "Sandbox")'
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps what a timed-out log printed and reports the timeout', async () => {
|
||||
const verdict = await readTccLogVerdict(DENIED_AT_MS, SUBJECT, async () => ({
|
||||
code: null,
|
||||
signal: 'SIGTERM',
|
||||
stdout: ndjson(HELPER_DOWNLOADS_REFUSED),
|
||||
stderr: '',
|
||||
timedOut: true
|
||||
}))
|
||||
expect(verdict).toMatchObject({ logAccess: 'timeout', authValue: 'denied' })
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'kills a hung log reader at its deadline',
|
||||
async () => {
|
||||
// Same spec, but a child that never exits on its own.
|
||||
const verdict = await readTccLogVerdict(DENIED_AT_MS, SUBJECT, (spec) =>
|
||||
runProcess({ ...spec, program: '/bin/sleep', args: ['60'] })
|
||||
)
|
||||
expect(verdict.logAccess).toBe('timeout')
|
||||
},
|
||||
15_000
|
||||
)
|
||||
|
||||
it('swallows a spawn failure', async () => {
|
||||
const verdict = await readTccLogVerdict(DENIED_AT_MS, SUBJECT, async () => {
|
||||
throw new Error('spawn ENOENT')
|
||||
})
|
||||
expect(verdict).toMatchObject({ logAccess: 'error', tccdAsked: 'unknown' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { runProcess } from '@orca/process-host'
|
||||
|
||||
type ProcessSpec = Parameters<typeof runProcess>[0]
|
||||
type ProcessResult = Awaited<ReturnType<typeof runProcess>>
|
||||
import {
|
||||
checkHelperSignatures,
|
||||
resetHelperSignatureChecksForTests
|
||||
} from '../tcc-denial-signature-checks'
|
||||
|
||||
const APP_REQUIREMENT =
|
||||
'identifier "com.stablyai.orca" and anchor apple generic and certificate leaf[subject.OU] = "6CX3WHS9HZ"'
|
||||
const HELPER =
|
||||
'/Users/user/Library/Application Support/orca/daemon-host/macos/terminal-host-1/app.noindex/Orca Terminal Host.app/Contents/MacOS/orca-terminal-host'
|
||||
|
||||
function result(code: number | null, stdout = '', stderr = '', timedOut = false): ProcessResult {
|
||||
return { code, signal: null, stdout, stderr, timedOut }
|
||||
}
|
||||
|
||||
type Replies = { liveVerify: ProcessResult; liveRequirement: string; diskVerify: ProcessResult }
|
||||
|
||||
function codesignFake(replies: Replies) {
|
||||
return vi.fn(async (spec: ProcessSpec): Promise<ProcessResult> => {
|
||||
const args = spec.args ?? []
|
||||
const target = args.at(-1) ?? ''
|
||||
if (args[0] === '--display') {
|
||||
return target.startsWith('+')
|
||||
? result(0, `designated => ${replies.liveRequirement}\n`)
|
||||
: result(0, `designated => ${APP_REQUIREMENT}\n`)
|
||||
}
|
||||
return target.startsWith('+') ? replies.liveVerify : replies.diskVerify
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetHelperSignatureChecksForTests()
|
||||
vi.spyOn(process, 'execPath', 'get').mockReturnValue('/Applications/Orca.app/Contents/MacOS/Orca')
|
||||
})
|
||||
|
||||
describe('checkHelperSignatures', () => {
|
||||
it('passes a live helper carrying the app requirement and verifies the copy bundle', async () => {
|
||||
const run = codesignFake({
|
||||
liveVerify: result(0),
|
||||
liveRequirement: APP_REQUIREMENT,
|
||||
diskVerify: result(1, '', 'a sealed resource is missing or invalid')
|
||||
})
|
||||
expect(await checkHelperSignatures(1206, HELPER, run)).toEqual({
|
||||
live: 'pass',
|
||||
diskCopy: 'fail'
|
||||
})
|
||||
expect(run).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: [
|
||||
'--verify',
|
||||
'--strict',
|
||||
'/Users/user/Library/Application Support/orca/daemon-host/macos/terminal-host-1/app.noindex/Orca Terminal Host.app'
|
||||
]
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('fails a live helper whose requirement differs from the app', async () => {
|
||||
const run = codesignFake({
|
||||
liveVerify: result(0),
|
||||
liveRequirement: 'identifier "com.stablyai.orca" and anchor apple generic',
|
||||
diskVerify: result(0)
|
||||
})
|
||||
expect((await checkHelperSignatures(1206, HELPER, run)).live).toBe('fail')
|
||||
})
|
||||
|
||||
it('reports error, not fail, for a gone pid, a timeout or a missing path', async () => {
|
||||
const gone = codesignFake({
|
||||
liveVerify: result(1, '', '+1206: host has no guest with the requested attributes'),
|
||||
liveRequirement: APP_REQUIREMENT,
|
||||
diskVerify: result(null, '', '', true)
|
||||
})
|
||||
expect(await checkHelperSignatures(1206, HELPER, gone)).toEqual({
|
||||
live: 'error',
|
||||
diskCopy: 'error'
|
||||
})
|
||||
const noPath = codesignFake({
|
||||
liveVerify: result(0),
|
||||
liveRequirement: APP_REQUIREMENT,
|
||||
diskVerify: result(0)
|
||||
})
|
||||
expect((await checkHelperSignatures(1206, null, noPath)).diskCopy).toBe('error')
|
||||
})
|
||||
})
|
||||
@@ -28,6 +28,7 @@ const MAIN_OWNED_TELEMETRY_EVENTS = new Set<EventName>([
|
||||
'daemon_audit_eligibility',
|
||||
'daemon_pty_cwd_denied',
|
||||
'daemon_pty_cwd_readable',
|
||||
'daemon_pty_cwd_denial_capture',
|
||||
'star_nag_outcome',
|
||||
'feature_interaction_usage_bucket_reached',
|
||||
'first_agent_interaction',
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// Wake-type signals that could precede a terminal-host folder denial; times only, kept in memory.
|
||||
// Electron-free: the desktop shell feeds it, and runtime-reachable daemon code reads it.
|
||||
export type WakeSignal = 'resume' | 'unlock-screen' | 'user-did-become-active'
|
||||
|
||||
const lastSeenAtMs = new Map<WakeSignal, number>()
|
||||
|
||||
export function recordWakeSignal(signal: WakeSignal, nowMs: number = Date.now()): void {
|
||||
lastSeenAtMs.set(signal, nowMs)
|
||||
}
|
||||
|
||||
/** Null when the signal has not fired since this app process started. */
|
||||
export function msSinceWakeSignal(signal: WakeSignal, nowMs: number): number | null {
|
||||
const at = lastSeenAtMs.get(signal)
|
||||
return at === undefined ? null : Math.max(0, nowMs - at)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { join } from 'node:path'
|
||||
import { AgentAwakeService } from '../power/agent-awake-service'
|
||||
import { normalizeComputerAwakeMode } from '../../shared/computer-awake-mode'
|
||||
import { registerSystemResumeBroadcast } from '../power/system-resume-broadcast'
|
||||
import { recordWakeSignal } from '../power/wake-signal-clock'
|
||||
import { readDesktopAwayState } from '../notifications/desktop-away-state'
|
||||
import {
|
||||
listCapableSharedControlSockets,
|
||||
@@ -30,12 +31,29 @@ import { runAfterFirstWindowShown } from './main-window/first-window-deferral'
|
||||
|
||||
const TELEMETRY_CLIENT_START_FALLBACK_MS = 15_000
|
||||
|
||||
function feedWakeSignalClock(): () => void {
|
||||
const onResume = (): void => recordWakeSignal('resume')
|
||||
const onUnlock = (): void => recordWakeSignal('unlock-screen')
|
||||
const onUserActive = (): void => recordWakeSignal('user-did-become-active')
|
||||
powerMonitor.on('resume', onResume)
|
||||
powerMonitor.on('unlock-screen', onUnlock)
|
||||
powerMonitor.on('user-did-become-active', onUserActive)
|
||||
return () => {
|
||||
powerMonitor.off('resume', onResume)
|
||||
powerMonitor.off('unlock-screen', onUnlock)
|
||||
powerMonitor.off('user-did-become-active', onUserActive)
|
||||
}
|
||||
}
|
||||
|
||||
export function initializeMainProcessObservers(): void {
|
||||
const store = state.store
|
||||
if (!store) {
|
||||
throw new Error('Store must be initialized before observers')
|
||||
}
|
||||
state.unsubscribeSystemResumeBroadcast = registerSystemResumeBroadcast()
|
||||
if (process.platform === 'darwin') {
|
||||
state.unsubscribeWakeSignalClock = feedWakeSignalClock()
|
||||
}
|
||||
state.stopDesktopPresenceReporter = startDesktopPresenceReporter({
|
||||
readAway: () => readDesktopAwayState(powerMonitor),
|
||||
listTargets: listCapableSharedControlSockets,
|
||||
|
||||
@@ -116,6 +116,7 @@ export const mainProcessState = {
|
||||
crashReports: null as CrashReportStore | null,
|
||||
unsubscribeAgentAwakeStatusChanges: null as (() => void) | null,
|
||||
unsubscribeSystemResumeBroadcast: null as (() => void) | null,
|
||||
unsubscribeWakeSignalClock: null as (() => void) | null,
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: widens the null slot to the stop function assigned by main-process-observers.
|
||||
stopDesktopPresenceReporter: null as (() => void) | null,
|
||||
watcherShutdownPromise: null as Promise<void> | null,
|
||||
|
||||
@@ -120,6 +120,8 @@ function installWillQuitHandler(): void {
|
||||
state.desktopPushService?.stop()
|
||||
state.unsubscribeSystemResumeBroadcast?.()
|
||||
state.unsubscribeSystemResumeBroadcast = null
|
||||
state.unsubscribeWakeSignalClock?.()
|
||||
state.unsubscribeWakeSignalClock = null
|
||||
state.stopDesktopPresenceReporter?.()
|
||||
state.stopDesktopPresenceReporter = null
|
||||
// Keep log-stream diagnostics alive through renderer quit vetoes.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// Enum vocabulary for macOS's own verdict at a confirmed terminal-host folder denial; no paths, pids or log text.
|
||||
|
||||
export const TCC_LOG_ACCESS_VALUES = ['ok', 'denied', 'timeout', 'truncated', 'error'] as const
|
||||
export type TccLogAccess = (typeof TCC_LOG_ACCESS_VALUES)[number]
|
||||
|
||||
export const YES_NO_VALUES = ['yes', 'no'] as const
|
||||
export type YesNo = (typeof YES_NO_VALUES)[number]
|
||||
|
||||
// `uncorrelated`: a failure for the shared app identifier that no line ties to this helper.
|
||||
export const REQUIREMENT_FAILURE_VALUES = ['yes', 'uncorrelated', 'no'] as const
|
||||
export type RequirementFailure = (typeof REQUIREMENT_FAILURE_VALUES)[number]
|
||||
|
||||
export const TCC_ASKED_VALUES = ['yes', 'no', 'unknown'] as const
|
||||
export type TccAsked = (typeof TCC_ASKED_VALUES)[number]
|
||||
|
||||
// tccd authValue: 0 denied, 1 unknown, 2 allowed, 3 limited.
|
||||
export const TCC_AUTH_VALUES = ['denied', 'unknown', 'allowed', 'limited', 'other', 'none'] as const
|
||||
export type TccAuthValue = (typeof TCC_AUTH_VALUES)[number]
|
||||
|
||||
// Raw tccd authReason numbers; their meanings are not documented by Apple.
|
||||
export const TCC_AUTH_REASONS = [
|
||||
'0',
|
||||
'1',
|
||||
'2',
|
||||
'3',
|
||||
'4',
|
||||
'5',
|
||||
'6',
|
||||
'7',
|
||||
'8',
|
||||
'9',
|
||||
'10',
|
||||
'11',
|
||||
'12',
|
||||
'other',
|
||||
'none'
|
||||
] as const
|
||||
export type TccAuthReason = (typeof TCC_AUTH_REASONS)[number]
|
||||
|
||||
export const TCC_SERVICE_VALUES = [
|
||||
'documents',
|
||||
'desktop',
|
||||
'downloads',
|
||||
'all_files',
|
||||
'other',
|
||||
'none'
|
||||
] as const
|
||||
export type TccService = (typeof TCC_SERVICE_VALUES)[number]
|
||||
|
||||
export const SIGNATURE_CHECK_VALUES = ['pass', 'fail', 'error'] as const
|
||||
export type SignatureCheck = (typeof SIGNATURE_CHECK_VALUES)[number]
|
||||
|
||||
export const HELPER_AGE_BUCKETS = [
|
||||
'<1m',
|
||||
'1-10m',
|
||||
'10-60m',
|
||||
'1-6h',
|
||||
'6-24h',
|
||||
'1-7d',
|
||||
'7d+',
|
||||
'unknown'
|
||||
] as const
|
||||
export type HelperAgeBucket = (typeof HELPER_AGE_BUCKETS)[number]
|
||||
|
||||
export const HELPER_ORIGIN_VALUES = ['adopted', 'spawned', 'unknown'] as const
|
||||
export type HelperOrigin = (typeof HELPER_ORIGIN_VALUES)[number]
|
||||
|
||||
export const GOOD_READ_COUNT_BUCKETS = ['0', '1', '2-5', '6+'] as const
|
||||
export type GoodReadCountBucket = (typeof GOOD_READ_COUNT_BUCKETS)[number]
|
||||
|
||||
export const ELAPSED_BUCKETS = [
|
||||
'never',
|
||||
'<10s',
|
||||
'10-60s',
|
||||
'1-5m',
|
||||
'5-30m',
|
||||
'30m-6h',
|
||||
'6h+'
|
||||
] as const
|
||||
export type ElapsedBucket = (typeof ELAPSED_BUCKETS)[number]
|
||||
|
||||
export const FULL_DISK_ACCESS_VALUES = ['granted', 'denied', 'unsupported', 'unknown'] as const
|
||||
export type FullDiskAccessValue = (typeof FULL_DISK_ACCESS_VALUES)[number]
|
||||
|
||||
export const FORK_FALLBACK_VALUES = [
|
||||
'none',
|
||||
'prepare-failed',
|
||||
'deadline',
|
||||
'bootstrap-refused',
|
||||
'exited-before-ready',
|
||||
'endpoint-taken',
|
||||
'os-too-old',
|
||||
'not-eligible',
|
||||
'unknown'
|
||||
] as const
|
||||
export type ForkFallbackValue = (typeof FORK_FALLBACK_VALUES)[number]
|
||||
|
||||
export const FOLDER_FLAG_VALUES = ['yes', 'no', 'unknown'] as const
|
||||
export type FolderFlag = (typeof FOLDER_FLAG_VALUES)[number]
|
||||
|
||||
export const ICLOUD_MANAGED_VALUES = ['yes', 'no', 'unknown', 'not_applicable'] as const
|
||||
export type IcloudManaged = (typeof ICLOUD_MANAGED_VALUES)[number]
|
||||
|
||||
export const VOLUME_TYPE_VALUES = [
|
||||
'apfs',
|
||||
'hfs',
|
||||
'smbfs',
|
||||
'nfs',
|
||||
'afpfs',
|
||||
'webdav',
|
||||
'msdos',
|
||||
'exfat',
|
||||
'other',
|
||||
'unknown'
|
||||
] as const
|
||||
export type VolumeType = (typeof VOLUME_TYPE_VALUES)[number]
|
||||
|
||||
const MINUTE_MS = 60_000
|
||||
const HOUR_MS = 60 * MINUTE_MS
|
||||
|
||||
export function bucketHelperAge(ageMs: number | null): HelperAgeBucket {
|
||||
if (ageMs === null || !Number.isFinite(ageMs) || ageMs < 0) {
|
||||
return 'unknown'
|
||||
}
|
||||
if (ageMs < MINUTE_MS) {
|
||||
return '<1m'
|
||||
}
|
||||
if (ageMs < 10 * MINUTE_MS) {
|
||||
return '1-10m'
|
||||
}
|
||||
if (ageMs < HOUR_MS) {
|
||||
return '10-60m'
|
||||
}
|
||||
if (ageMs < 6 * HOUR_MS) {
|
||||
return '1-6h'
|
||||
}
|
||||
if (ageMs < 24 * HOUR_MS) {
|
||||
return '6-24h'
|
||||
}
|
||||
return ageMs < 7 * 24 * HOUR_MS ? '1-7d' : '7d+'
|
||||
}
|
||||
|
||||
export function bucketElapsed(elapsedMs: number | null): ElapsedBucket {
|
||||
if (elapsedMs === null || !Number.isFinite(elapsedMs) || elapsedMs < 0) {
|
||||
return 'never'
|
||||
}
|
||||
if (elapsedMs < 10_000) {
|
||||
return '<10s'
|
||||
}
|
||||
if (elapsedMs < MINUTE_MS) {
|
||||
return '10-60s'
|
||||
}
|
||||
if (elapsedMs < 5 * MINUTE_MS) {
|
||||
return '1-5m'
|
||||
}
|
||||
if (elapsedMs < 30 * MINUTE_MS) {
|
||||
return '5-30m'
|
||||
}
|
||||
return elapsedMs < 6 * HOUR_MS ? '30m-6h' : '6h+'
|
||||
}
|
||||
|
||||
export function bucketGoodReadCount(count: number): GoodReadCountBucket {
|
||||
if (count <= 0) {
|
||||
return '0'
|
||||
}
|
||||
if (count === 1) {
|
||||
return '1'
|
||||
}
|
||||
return count <= 5 ? '2-5' : '6+'
|
||||
}
|
||||
@@ -20,8 +20,28 @@ import {
|
||||
DAEMON_CODE_IDENTITY_VALUES,
|
||||
DAEMON_PTY_CWD_CLASSES,
|
||||
DAEMON_SPAWNER_PATH_CLASSES,
|
||||
DAEMON_TCC_ATTRIBUTION_VALUES
|
||||
DAEMON_TCC_ATTRIBUTION_VALUES,
|
||||
MAC_TCC_FOLDER_CLASSES
|
||||
} from './daemon-adoption-telemetry'
|
||||
import {
|
||||
ELAPSED_BUCKETS,
|
||||
FOLDER_FLAG_VALUES,
|
||||
FORK_FALLBACK_VALUES,
|
||||
FULL_DISK_ACCESS_VALUES,
|
||||
GOOD_READ_COUNT_BUCKETS,
|
||||
HELPER_AGE_BUCKETS,
|
||||
HELPER_ORIGIN_VALUES,
|
||||
ICLOUD_MANAGED_VALUES,
|
||||
REQUIREMENT_FAILURE_VALUES,
|
||||
SIGNATURE_CHECK_VALUES,
|
||||
TCC_ASKED_VALUES,
|
||||
TCC_AUTH_REASONS,
|
||||
TCC_AUTH_VALUES,
|
||||
TCC_LOG_ACCESS_VALUES,
|
||||
TCC_SERVICE_VALUES,
|
||||
VOLUME_TYPE_VALUES,
|
||||
YES_NO_VALUES
|
||||
} from './daemon-tcc-denial-capture'
|
||||
import { errorClassSchema, settingsChangedKeySchema } from './telemetry-property-schemas'
|
||||
|
||||
// Enum-only start-failure signals diagnose fleet outages without sending raw stderr (v1.4.129-rc.1).
|
||||
@@ -101,6 +121,34 @@ export const daemonPtyCwdVerdictSchema = z
|
||||
.object({ cwd_class: z.enum(DAEMON_PTY_CWD_CLASSES), ...daemonOriginProps })
|
||||
.strict()
|
||||
|
||||
// macOS's own verdict at a confirmed denial, once per helper and folder class; raw lines stay in a local file.
|
||||
export const daemonPtyCwdDenialCaptureSchema = z
|
||||
.object({
|
||||
cwd_class: z.enum(MAC_TCC_FOLDER_CLASSES),
|
||||
log_access: z.enum(TCC_LOG_ACCESS_VALUES),
|
||||
tccd_asked: z.enum(TCC_ASKED_VALUES),
|
||||
auth_value: z.enum(TCC_AUTH_VALUES),
|
||||
auth_reason: z.enum(TCC_AUTH_REASONS),
|
||||
service: z.enum(TCC_SERVICE_VALUES),
|
||||
requirement_failure: z.enum(REQUIREMENT_FAILURE_VALUES),
|
||||
kernel_deny: z.enum(YES_NO_VALUES),
|
||||
live_signature: z.enum(SIGNATURE_CHECK_VALUES),
|
||||
disk_copy_signature: z.enum(SIGNATURE_CHECK_VALUES),
|
||||
helper_age_bucket: z.enum(HELPER_AGE_BUCKETS),
|
||||
helper_origin: z.enum(HELPER_ORIGIN_VALUES),
|
||||
good_reads_bucket: z.enum(GOOD_READ_COUNT_BUCKETS),
|
||||
since_good_read_bucket: z.enum(ELAPSED_BUCKETS),
|
||||
since_resume_bucket: z.enum(ELAPSED_BUCKETS),
|
||||
since_unlock_bucket: z.enum(ELAPSED_BUCKETS),
|
||||
since_user_active_bucket: z.enum(ELAPSED_BUCKETS),
|
||||
full_disk_access: z.enum(FULL_DISK_ACCESS_VALUES),
|
||||
fork_fallback: z.enum(FORK_FALLBACK_VALUES),
|
||||
folder_dataless: z.enum(FOLDER_FLAG_VALUES),
|
||||
folder_icloud: z.enum(ICLOUD_MANAGED_VALUES),
|
||||
volume_type: z.enum(VOLUME_TYPE_VALUES)
|
||||
})
|
||||
.strict()
|
||||
|
||||
// Count notice exposure/action/restart outcome against daemon_pty_cwd_denied incidence (STA-7948).
|
||||
export const daemonFolderAccessNoticeSchema = z
|
||||
.object({
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
daemonAuditEligibilitySchema,
|
||||
daemonFolderAccessNoticeSchema,
|
||||
daemonLifecycleSchema,
|
||||
daemonPtyCwdDenialCaptureSchema,
|
||||
daemonPtyCwdVerdictSchema,
|
||||
daemonStartFailedSchema,
|
||||
mainThreadHangDetectedSchema,
|
||||
@@ -168,6 +169,7 @@ export const eventSchemas = {
|
||||
daemon_async_io_health: daemonAsyncIoHealthSchema,
|
||||
daemon_pty_cwd_denied: daemonPtyCwdVerdictSchema,
|
||||
daemon_pty_cwd_readable: daemonPtyCwdVerdictSchema,
|
||||
daemon_pty_cwd_denial_capture: daemonPtyCwdDenialCaptureSchema,
|
||||
daemon_folder_access_notice: daemonFolderAccessNoticeSchema,
|
||||
daemon_audit_eligibility: daemonAuditEligibilitySchema,
|
||||
runtime_rpc_start_failed: runtimeRpcStartFailedSchema,
|
||||
|
||||
Reference in New Issue
Block a user