hermes-agent/apps/desktop/electron/hardening.test.ts
ethernet 890bbbda1f Merge remote-tracking branch 'origin/main' into ethie/pm-clean
# Conflicts:
#	apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts
#	apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts
#	apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts
#	apps/desktop/e2e/bot-mode-roster-localized.spec.ts
#	apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
#	apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
#	apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts
#	apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts
#	apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts
#	apps/desktop/e2e/bot-roster-user-sections.spec.ts
#	apps/desktop/e2e/bot-routines-pane-narrow.spec.ts
#	apps/desktop/e2e/bot-row-open-recent-session.spec.ts
#	apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts
#	apps/desktop/e2e/group-composer-auto-grow.spec.ts
#	apps/desktop/e2e/group-create-gate-remote-roster.spec.ts
#	apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts
#	apps/desktop/e2e/hosted-room-backend-continuity.spec.ts
#	apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts
#	apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts
#	apps/desktop/e2e/worktree-branch-status.spec.ts
#	apps/desktop/electron/backend-probes.test.ts
#	apps/desktop/electron/connection-apply.test.ts
#	apps/desktop/electron/desktop-electron-pin.test.ts
#	apps/desktop/electron/desktop-uninstall.test.ts
#	apps/desktop/electron/gateway-file-download-transport.test.ts
#	apps/desktop/electron/gateway-stop-before-update.test.ts
#	apps/desktop/electron/github-api-auth.test.ts
#	apps/desktop/electron/registry-primary-profile-scope.test.ts
#	apps/desktop/electron/update-api-check.test.ts
#	apps/desktop/electron/update-handoff-marker.test.ts
#	apps/desktop/electron/venv-blocker-scan.test.ts
#	apps/desktop/scripts/after-extract.test.mjs
#	apps/desktop/scripts/local-pack-publish.test.mjs
#	apps/desktop/scripts/tasks-scroll.test.mjs
#	apps/desktop/src/app/settings/model-settings.test.tsx
#	apps/desktop/src/app/updates-overlay.blockers.test.tsx
#	apps/desktop/src/components/desktop-install-overlay.test.tsx
#	apps/desktop/src/lib/update-copy.test.ts
#	scripts/ci/check_os_marker_fakes.py
#	tests-js/desktop-mac-usage-descriptions.test.ts
#	tests-js/node-engine-alignment.test.ts
#	tests/agent/lsp/test_install_and_lint_fixes.py
#	tests/agent/test_command_token_source.py
#	tests/agent/test_compression_boundary_hook.py
#	tests/agent/test_create_openai_client_ssl_verify.py
#	tests/agent/test_custom_provider_ca_probes.py
#	tests/agent/test_endpoint_blackhole.py
#	tests/agent/test_estimator_parity.py
#	tests/agent/test_in_place_compaction.py
#	tests/agent/test_moa_loop_mode.py
#	tests/agent/test_model_metadata.py
#	tests/agent/test_skill_session_platform_gate.py
#	tests/agent/test_skill_utils.py
#	tests/agent/test_ssl_ca_guard.py
#	tests/computer_use/test_doctor.py
#	tests/cron/test_codex_execution_paths.py
#	tests/cron/test_cron_bot_chat_delivery.py
#	tests/cron/test_cron_script.py
#	tests/cron/test_media_delivery_parity.py
#	tests/cron/test_misfire_catchup.py
#	tests/cron/test_parallel_pool.py
#	tests/cron/test_recurring_eagain_redispatch.py
#	tests/gateway/test_choice_picker.py
#	tests/gateway/test_control_socket_windows_live.py
#	tests/gateway/test_dingtalk.py
#	tests/gateway/test_feishu.py
#	tests/gateway/test_feishu_onboard.py
#	tests/gateway/test_gateway_shutdown.py
#	tests/gateway/test_matrix.py
#	tests/gateway/test_model_command_custom_providers.py
#	tests/gateway/test_reasoning_command.py
#	tests/gateway/test_runtime_footer.py
#	tests/gateway/test_session.py
#	tests/gateway/test_session_hygiene.py
#	tests/gateway/test_status.py
#	tests/gateway/test_teams.py
#	tests/gateway/test_turn_lease.py
#	tests/gateway/test_whatsapp_connect.py
#	tests/hermes_cli/test_approvals_command.py
#	tests/hermes_cli/test_auth_store_lock_concurrent.py
#	tests/hermes_cli/test_backup.py
#	tests/hermes_cli/test_banner_git_state.py
#	tests/hermes_cli/test_certifi_repair.py
#	tests/hermes_cli/test_cmd_update.py
#	tests/hermes_cli/test_compat_manifest_targets.py
#	tests/hermes_cli/test_computer_use_cli.py
#	tests/hermes_cli/test_cpr_local_leak.py
#	tests/hermes_cli/test_dashboard_auth_gate.py
#	tests/hermes_cli/test_dashboard_procs_kill_grace.py
#	tests/hermes_cli/test_desktop_lifecycle_windows_live.py
#	tests/hermes_cli/test_doctor.py
#	tests/hermes_cli/test_doctor_command_install.py
#	tests/hermes_cli/test_fleet_config_migration_windows_live.py
#	tests/hermes_cli/test_gateway.py
#	tests/hermes_cli/test_gateway_platform_gating.py
#	tests/hermes_cli/test_gateway_restart_loop.py
#	tests/hermes_cli/test_gateway_task_probe.py
#	tests/hermes_cli/test_gateway_wsl.py
#	tests/hermes_cli/test_gui_command.py
#	tests/hermes_cli/test_install_cua_driver.py
#	tests/hermes_cli/test_kanban_db.py
#	tests/hermes_cli/test_lazy_command_exports.py
#	tests/hermes_cli/test_lazy_refresh_venv_repair.py
#	tests/hermes_cli/test_linux_desktop_entry.py
#	tests/hermes_cli/test_local_runtime.py
#	tests/hermes_cli/test_local_runtime_updates.py
#	tests/hermes_cli/test_managed_uv.py
#	tests/hermes_cli/test_mcp_reload_confirm_gate.py
#	tests/hermes_cli/test_nous_subscription.py
#	tests/hermes_cli/test_npm_engine.py
#	tests/hermes_cli/test_personality_none.py
#	tests/hermes_cli/test_pet_toggle.py
#	tests/hermes_cli/test_plan_reconciliation_windows_live.py
#	tests/hermes_cli/test_plugin_event_bus.py
#	tests/hermes_cli/test_plugin_manifest_v2.py
#	tests/hermes_cli/test_plugin_packs.py
#	tests/hermes_cli/test_plugins_cmd.py
#	tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py
#	tests/hermes_cli/test_process_identity.py
#	tests/hermes_cli/test_profiles.py
#	tests/hermes_cli/test_profiles_sidebar_cache.py
#	tests/hermes_cli/test_pty_bridge.py
#	tests/hermes_cli/test_resolve_turn_limit.py
#	tests/hermes_cli/test_serve_runtime_inventory.py
#	tests/hermes_cli/test_session_vacuum_config.py
#	tests/hermes_cli/test_set_config_value.py
#	tests/hermes_cli/test_signal_handler_kanban_worker.py
#	tests/hermes_cli/test_slash_confirm_windows.py
#	tests/hermes_cli/test_stale_pid_guard.py
#	tests/hermes_cli/test_startup_fast_guards.py
#	tests/hermes_cli/test_status.py
#	tests/hermes_cli/test_telegram_managed_bot.py
#	tests/hermes_cli/test_tools_config.py
#	tests/hermes_cli/test_update_apply_shallow_count.py
#	tests/hermes_cli/test_update_autostash.py
#	tests/hermes_cli/test_update_concurrent_quarantine.py
#	tests/hermes_cli/test_update_fetch_failure_classifier.py
#	tests/hermes_cli/test_update_fleet_probe_resume_token.py
#	tests/hermes_cli/test_update_handoff_backend_reap.py
#	tests/hermes_cli/test_update_handoff_desktop_rebuild.py
#	tests/hermes_cli/test_update_head_moved_gate.py
#	tests/hermes_cli/test_update_host_obligation.py
#	tests/hermes_cli/test_update_import_guard.py
#	tests/hermes_cli/test_update_interrupted_recovery.py
#	tests/hermes_cli/test_update_inventory.py
#	tests/hermes_cli/test_update_launchd_unloaded_gateway.py
#	tests/hermes_cli/test_update_missing_configured_deps.py
#	tests/hermes_cli/test_update_modified_notice.py
#	tests/hermes_cli/test_update_multiplex_migration_hook.py
#	tests/hermes_cli/test_update_no_gateway_restart.py
#	tests/hermes_cli/test_update_orphan_backend_reap.py
#	tests/hermes_cli/test_update_parked_branch_guard.py
#	tests/hermes_cli/test_update_post_pull_syntax_guard.py
#	tests/hermes_cli/test_update_receipt.py
#	tests/hermes_cli/test_update_self_lock.py
#	tests/hermes_cli/test_update_shim_fail_closed.py
#	tests/hermes_cli/test_update_shim_self_lock.py
#	tests/hermes_cli/test_update_sqlite_remediation.py
#	tests/hermes_cli/test_update_stale_dashboard.py
#	tests/hermes_cli/test_update_stale_virtualenv.py
#	tests/hermes_cli/test_update_venv_health.py
#	tests/hermes_cli/test_update_venv_ownership_preflight.py
#	tests/hermes_cli/test_update_wedged_gateway.py
#	tests/hermes_cli/test_update_yes_flag.py
#	tests/hermes_cli/test_update_zip_two_phase.py
#	tests/hermes_cli/test_urllib_security.py
#	tests/hermes_cli/test_ux_messages_auth_config.py
#	tests/hermes_cli/test_ux_messages_startup.py
#	tests/hermes_cli/test_venv_holder_classifier.py
#	tests/hermes_cli/test_verify_console_scripts.py
#	tests/hermes_cli/test_verify_core_dependencies.py
#	tests/hermes_cli/test_web_server.py
#	tests/hermes_cli/test_web_server_console_ws.py
#	tests/hermes_cli/test_web_server_ws_ping.py
#	tests/hermes_cli/test_web_ui_build.py
#	tests/hermes_state/test_fts_rebuild_admission.py
#	tests/hermes_state/test_hermes_state.py
#	tests/plugins/memory/test_memory_lazy_install.py
#	tests/plugins/test_google_meet_plugin.py
#	tests/plugins/test_langfuse_plugin.py
#	tests/plugins/test_security_guidance_plugin.py
#	tests/plugins/test_transform_llm_output_hook.py
#	tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py
#	tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
#	tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
#	tests/scripts/install/test_install_clone_throttle_fallback.py
#	tests/scripts/install/test_install_lockfile_churn.py
#	tests/scripts/install/test_install_no_initial_commit.py
#	tests/scripts/install/test_install_sh_browser_install.py
#	tests/scripts/install/test_install_sh_node_prerelease.py
#	tests/scripts/install/test_install_sh_symlink_stomp.py
#	tests/scripts/install/test_install_sh_uv_lock_config.py
#	tests/scripts/install/test_install_unmerged_index.py
#	tests/scripts/test_contributor_map.py
#	tests/scripts/test_run_tests_parallel.py
#	tests/skills/test_competitor_news_monitor_skill.py
#	tests/skills/test_document_to_action_items_skill.py
#	tests/skills/test_google_workspace_setup.py
#	tests/skills/test_google_workspace_setup_deps.py
#	tests/skills/test_grounded_citations_skill.py
#	tests/skills/test_ip_as_logo_skill.py
#	tests/skills/test_live_dashboard_skill.py
#	tests/skills/test_mcp_oauth_remote_gateway_skill.py
#	tests/skills/test_office_document_skills.py
#	tests/skills/test_openclaw_migration.py
#	tests/skills/test_product_price_monitor_skill.py
#	tests/skills/test_scrollcraft_skill.py
#	tests/skills/test_setup_wizard_generator_skill.py
#	tests/skills/test_weekly_review_planning_skill.py
#	tests/test_engines_satisfiable.py
#	tests/test_fast_safe_load.py
#	tests/test_hermes_bootstrap.py
#	tests/test_hermes_constants.py
#	tests/test_hermes_logging.py
#	tests/test_managed_runtime_resolution.py
#	tests/test_model_tools_async_bridge.py
#	tests/test_packaging_build_guard.py
#	tests/test_packaging_metadata.py
#	tests/test_yaml_indent_consistency.py
#	tests/tools/test_approval_timeout_overflow.py
#	tests/tools/test_base_environment.py
#	tests/tools/test_bot_mode_dm.py
#	tests/tools/test_browser_chromium_check.py
#	tests/tools/test_browser_hardening.py
#	tests/tools/test_browser_homebrew_paths.py
#	tests/tools/test_browser_npx_warmup.py
#	tests/tools/test_browser_orphan_reaper.py
#	tests/tools/test_browser_real_profile.py
#	tests/tools/test_browser_use_cli.py
#	tests/tools/test_clipboard.py
#	tests/tools/test_code_execution.py
#	tests/tools/test_code_execution_modes.py
#	tests/tools/test_code_execution_windows_env.py
#	tests/tools/test_computer_use.py
#	tests/tools/test_delegate_liveness_timeout.py
#	tests/tools/test_execute_code_approval_cluster.py
#	tests/tools/test_execution_flag_detection.py
#	tests/tools/test_fal_common.py
#	tests/tools/test_file_operations.py
#	tests/tools/test_file_tools.py
#	tests/tools/test_file_tools_cwd_resolution.py
#	tests/tools/test_file_tools_live.py
#	tests/tools/test_lazy_deps.py
#	tests/tools/test_lazy_deps_durable_target.py
#	tests/tools/test_lazy_deps_managed.py
#	tests/tools/test_local_env_blocklist.py
#	tests/tools/test_local_tempdir.py
#	tests/tools/test_macos_protected_search.py
#	tests/tools/test_mcp_npx_cached_bin.py
#	tests/tools/test_oneshot_completion_linger.py
#	tests/tools/test_process_registry.py
#	tests/tools/test_read_file_schema_gating.py
#	tests/tools/test_skill_improvements.py
#	tests/tools/test_skills_sync.py
#	tests/tools/test_termux_api_detection.py
#	tests/tools/test_tirith_security.py
#	tests/tools/test_transcription_tools.py
#	tests/tools/test_tts_streaming.py
#	tests/tools/test_wake_word.py
#	tests/tui_gateway/test_compute_host_borrowed_lease.py
#	tests/tui_gateway/test_compute_host_turn_protocol.py
#	tests/tui_gateway/test_isolated_orphan_activity.py
#	tests/tui_gateway/test_protocol.py
#	tests/tui_gateway/test_slash_worker_profile_home.py
#	tests/tui_gateway/test_subprocess_encoding.py
#	tests/tui_gateway/test_tui_gateway_server.py
#	ui-tui/src/__tests__/terminalParity.test.ts
#	ui-tui/src/__tests__/termuxComposerLayout.test.ts
#	ui-tui/src/__tests__/textInputFastEcho.test.ts
2026-09-23 07:02:44 -04:00

1051 lines
36 KiB
TypeScript

import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { test } from 'vitest'
import {
ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
clampDataUrlReadMaxMb,
DATA_URL_READ_DEFAULT_MAX_MB,
dataUrlReadMaxBytesFromMb,
DEFAULT_FETCH_TIMEOUT_MS,
enableBasicPasswordStoreEncryption,
encryptDesktopSecret,
homeRelativeAttachmentCandidates,
readFileDataUrlForIpc,
resolveDirectoryForIpc,
resolvePersistedRemoteToken,
resolveReadableFileForIpc,
resolveRemoteTokenPlainText,
resolveRequestedPathForIpc,
resolveTimeoutMs,
SAFE_STORAGE_ENCODING,
SECRET_FILE_MODE,
sensitiveFileBlockReason,
tightenSecretFileMode,
writeSecretFileAtomic
} from './hardening'
/**
* Real temp dir per test: the property under test IS the on-disk mode after a
* temp-file-then-rename, which a mocked fs would assert into existence rather
* than verify. `platform` is still injected so the Windows branch is coverable
* from a POSIX run.
*/
function withTempDir(run: (dir: string) => void) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-secret-file-'))
try {
run(dir)
} finally {
fs.rmSync(dir, { force: true, recursive: true })
}
}
function modeOf(filePath: string) {
return fs.statSync(filePath).mode & 0o777
}
/**
* No file other than the target may survive a write, and nothing left in the
* directory may contain the payload. Asserts the CONTRACT (no readable debris)
* instead of a literal directory listing, so adding a lock file or renaming the
* staging file does not break the test.
*/
function assertNoSecretDebris(dir: string, targetName: string, secret: string) {
for (const name of fs.readdirSync(dir)) {
if (name === targetName) {
continue
}
// Substring, not RegExp: a real token can contain regex metacharacters.
assert.equal(
fs.readFileSync(path.join(dir, name), 'utf8').includes(secret),
false,
`leftover file ${name} still contains the secret`
)
}
}
async function rejectsWithCode(promise, code: string) {
await assert.rejects(promise, (error: any) => {
assert.equal(error?.code, code)
return true
})
}
test('clampDataUrlReadMaxMb defaults and bounds the attach size preference', () => {
assert.equal(clampDataUrlReadMaxMb(undefined), DATA_URL_READ_DEFAULT_MAX_MB)
assert.equal(clampDataUrlReadMaxMb(0), 1)
assert.equal(clampDataUrlReadMaxMb(256), 256)
assert.equal(clampDataUrlReadMaxMb(99999), 4096)
assert.equal(dataUrlReadMaxBytesFromMb(16), 16 * 1024 * 1024)
})
test('attachment data URL helper reads bytes above the preview default without changing that limit', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-large-attachment-'))
const source = path.join(tempDir, 'large.bin')
const previewLimit = dataUrlReadMaxBytesFromMb(DATA_URL_READ_DEFAULT_MAX_MB)
const content = Buffer.alloc(previewLimit + 1024, 0x5a)
try {
fs.writeFileSync(source, content)
await assert.rejects(
resolveReadableFileForIpc(source, {
maxBytes: previewLimit,
purpose: 'File preview'
}),
/file is too large/
)
const dataUrl = await readFileDataUrlForIpc(source, {
maxBytes: ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
mimeType: 'application/octet-stream',
purpose: 'Attachment upload'
})
assert.match(dataUrl, /^data:application\/octet-stream;base64,/)
assert.deepEqual(Buffer.from(dataUrl.slice(dataUrl.indexOf(',') + 1), 'base64'), content)
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('resolveTimeoutMs falls back to defaults and accepts overrides', () => {
assert.equal(resolveTimeoutMs(undefined), DEFAULT_FETCH_TIMEOUT_MS)
assert.equal(resolveTimeoutMs(0), DEFAULT_FETCH_TIMEOUT_MS)
assert.equal(resolveTimeoutMs(-25), DEFAULT_FETCH_TIMEOUT_MS)
assert.equal(resolveTimeoutMs('2750'), 2750)
})
test('encryptDesktopSecret requires available secure storage', () => {
assert.equal(
encryptDesktopSecret('', { isEncryptionAvailable: () => true, encryptString: () => Buffer.alloc(0) }),
null
)
assert.throws(
() => encryptDesktopSecret('token', { isEncryptionAvailable: () => false, encryptString: () => Buffer.alloc(0) }),
/Secure token storage is unavailable/
)
})
test('encryptDesktopSecret stores safeStorage base64 payload', () => {
const secret = encryptDesktopSecret('token-123', {
isEncryptionAvailable: () => true,
encryptString: value => Buffer.from(`enc:${value}`, 'utf8')
})
// Contract: the payload is tagged with the SAME constant main's
// decryptDesktopSecret dispatches on, and `value` is the keychain ciphertext
// base64'd — not the token itself.
assert.equal(secret?.encoding, SAFE_STORAGE_ENCODING)
assert.equal(Buffer.from(String(secret?.value), 'base64').toString('utf8'), 'enc:token-123')
assert.doesNotMatch(String(secret?.value), /token-123/, 'the plaintext is not recoverable from the payload')
})
// ─── Owner-only credential files (connection.json) ─────────────────────────
test.runIf(process.platform !== 'win32')(
'writeSecretFileAtomic creates the file owner-only, not at the 0644 umask default',
() => {
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
const payload = JSON.stringify({ remote: { token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' } } })
writeSecretFileAtomic(target, payload)
assert.equal(modeOf(target), SECRET_FILE_MODE)
assert.equal(modeOf(target) & 0o077, 0, 'no group/other bits')
assert.equal(fs.readFileSync(target, 'utf8'), payload, 'content round-trips')
assertNoSecretDebris(dir, 'connection.json', 'BLOB')
})
}
)
test('encryptDesktopSecret allows plain-text opt-in when encryption is unavailable', () => {
const secret = encryptDesktopSecret(
'token',
{ isEncryptionAvailable: () => false, encryptString: () => Buffer.alloc(0) },
{ allowPlainText: true }
)
assert.deepEqual(secret, { encoding: 'plain', value: 'token' })
})
test('encryptDesktopSecret keeps encrypting when available even with the plain-text opt-in', () => {
const secret = encryptDesktopSecret(
'token-123',
{ isEncryptionAvailable: () => true, encryptString: value => Buffer.from(`enc:${value}`, 'utf8') },
{ allowPlainText: true }
)
assert.deepEqual(secret, {
encoding: 'safeStorage',
value: Buffer.from('enc:token-123', 'utf8').toString('base64')
})
})
test('encryptDesktopSecret returns null for an empty value even with the plain-text opt-in', () => {
assert.equal(
encryptDesktopSecret(
'',
{ isEncryptionAvailable: () => false, encryptString: () => Buffer.alloc(0) },
{ allowPlainText: true }
),
null
)
})
test('enableBasicPasswordStoreEncryption flips the flag once on linux with --password-store=basic', () => {
const calls: boolean[] = []
const safeStorageApi = {
setUsePlainTextEncryption: (value: boolean) => calls.push(value)
}
const result = enableBasicPasswordStoreEncryption({
platform: 'linux',
passwordStoreSwitch: 'basic',
safeStorageApi
})
assert.equal(result, true)
assert.deepEqual(calls, [true])
})
test('enableBasicPasswordStoreEncryption ignores non-basic password-store values on linux', () => {
for (const passwordStoreSwitch of ['gnome-libsecret', '', undefined]) {
const calls: unknown[] = []
const safeStorageApi = {
setUsePlainTextEncryption: () => calls.push('called')
}
const result = enableBasicPasswordStoreEncryption({
platform: 'linux',
passwordStoreSwitch,
safeStorageApi
})
assert.equal(result, false, `value ${JSON.stringify(passwordStoreSwitch)} must not enable plain text`)
assert.deepEqual(calls, [])
}
})
test('enableBasicPasswordStoreEncryption never enables plain text off linux even with --password-store=basic', () => {
for (const platform of ['win32', 'darwin']) {
const calls: unknown[] = []
const safeStorageApi = {
setUsePlainTextEncryption: () => calls.push('called')
}
const result = enableBasicPasswordStoreEncryption({
platform,
passwordStoreSwitch: 'basic',
safeStorageApi
})
assert.equal(result, false, `platform ${platform} must not enable plain text`)
assert.deepEqual(calls, [])
}
})
test('enableBasicPasswordStoreEncryption tolerates a missing setUsePlainTextEncryption method', () => {
assert.equal(
enableBasicPasswordStoreEncryption({ platform: 'linux', passwordStoreSwitch: 'basic', safeStorageApi: {} }),
false
)
assert.equal(
enableBasicPasswordStoreEncryption({ platform: 'linux', passwordStoreSwitch: 'basic', safeStorageApi: undefined }),
false
)
})
test('enableBasicPasswordStoreEncryption swallows a throwing setUsePlainTextEncryption', () => {
const safeStorageApi = {
setUsePlainTextEncryption: () => {
throw new Error('backend not ready')
}
}
assert.equal(
enableBasicPasswordStoreEncryption({ platform: 'linux', passwordStoreSwitch: 'basic', safeStorageApi }),
false
)
})
test('resolvePersistedRemoteToken stores plain text end-to-end only with the explicit opt-in', () => {
const unavailableSafeStorage = { isEncryptionAvailable: () => false, encryptString: () => Buffer.alloc(0) }
const encryptSecret = (value: string, options: any) => encryptDesktopSecret(value, unavailableSafeStorage, options)
assert.deepEqual(
resolvePersistedRemoteToken({
incomingToken: 'token',
persistToken: true,
existingToken: undefined,
allowPlainText: true,
encryptSecret
}),
{ encoding: 'plain', value: 'token' }
)
// Only strict boolean true opts in; undefined, false, and truthy-non-true
// values must all keep the secure-storage requirement (which throws when the
// keyring is unavailable).
for (const allowPlainText of [undefined, false, 1, 'yes']) {
assert.throws(
() =>
resolvePersistedRemoteToken({
incomingToken: 'token',
persistToken: true,
existingToken: undefined,
allowPlainText,
encryptSecret
}),
/Secure token storage is unavailable/,
`allowPlainText ${JSON.stringify(allowPlainText)} must not enable plain-text storage`
)
}
})
test('resolvePersistedRemoteToken keeps encrypting when the keyring is available even with the opt-in', () => {
const availableSafeStorage = {
isEncryptionAvailable: () => true,
encryptString: (value: string) => Buffer.from(`enc:${value}`, 'utf8')
}
const encryptSecret = (value: string, options: any) => encryptDesktopSecret(value, availableSafeStorage, options)
assert.deepEqual(
resolvePersistedRemoteToken({
incomingToken: 'token-123',
persistToken: true,
existingToken: undefined,
allowPlainText: true,
encryptSecret
}),
{ encoding: 'safeStorage', value: Buffer.from('enc:token-123', 'utf8').toString('base64') }
)
})
test('resolvePersistedRemoteToken passes the token through untouched on the transient path', () => {
let called = false
const encryptSecret = () => {
called = true
return null
}
assert.deepEqual(
resolvePersistedRemoteToken({
incomingToken: 'token',
persistToken: false,
existingToken: { encoding: 'safeStorage', value: 'stale' },
allowPlainText: false,
encryptSecret
}),
{ encoding: 'plain', value: 'token' }
)
assert.equal(called, false, 'the transient test-connection path must not touch secure storage')
})
test('resolvePersistedRemoteToken keeps the existing token when no new token is supplied', () => {
let called = false
const encryptSecret = () => {
called = true
return null
}
const existingToken = { encoding: 'safeStorage', value: 'kept' }
assert.equal(
resolvePersistedRemoteToken({
incomingToken: '',
persistToken: true,
existingToken,
allowPlainText: true,
encryptSecret
}),
existingToken
)
assert.equal(called, false, 'an empty incoming token must not re-encrypt anything')
})
test('resolveRemoteTokenPlainText stays silent in the keychain-opt-out default', () => {
// #117269: with encryption opted out (the default), plain text is the CHOSEN
// mode and probeSecureTokenStorage reports availability on purpose — every
// saved token is plain here, so warning off the encoding alone would fire for
// every default user.
assert.equal(
resolveRemoteTokenPlainText({
envOverride: false,
token: { encoding: 'plain', value: 'token' },
secureTokenStorage: true
}),
false
)
})
test('resolveRemoteTokenPlainText warns only when the token is plain and the machine cannot secure it', () => {
// The genuine degraded state the banner is for: the keyring has gone away
// (secureTokenStorage false) while a plain token sits on disk.
assert.equal(
resolveRemoteTokenPlainText({
envOverride: false,
token: { encoding: 'plain', value: 'token' },
secureTokenStorage: false
}),
true
)
// An encrypted token never warns, whatever availability reports.
for (const secureTokenStorage of [true, false]) {
assert.equal(
resolveRemoteTokenPlainText({
envOverride: false,
token: { encoding: 'safeStorage', value: 'blob' },
secureTokenStorage
}),
false
)
}
// A missing token, or an absent availability signal, never manufactures a
// warning — the strict `=== false` match.
assert.equal(resolveRemoteTokenPlainText({ envOverride: false, token: undefined, secureTokenStorage: false }), false)
assert.equal(
resolveRemoteTokenPlainText({ envOverride: false, token: { encoding: 'plain' }, secureTokenStorage: undefined }),
false
)
assert.equal(resolveRemoteTokenPlainText({}), false)
// The env override supplies its token from the environment, never the saved
// block, so a plain stored blob must not warn while the override is active.
assert.equal(
resolveRemoteTokenPlainText({
envOverride: true,
token: { encoding: 'plain', value: 'token' },
secureTokenStorage: false
}),
false
)
})
test.runIf(process.platform !== 'win32')(
'writeSecretFileAtomic does not inherit loose bits from a stale temp file',
() => {
// renameSync keeps the TEMP file's permissions, and writeFileSync's `mode`
// is ignored when the path already exists — so a temp left by a crashed
// earlier write would otherwise hand 0644 straight to the target.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
fs.writeFileSync(`${target}.tmp`, 'stale', { mode: 0o666 })
assert.notEqual(modeOf(`${target}.tmp`), SECRET_FILE_MODE)
writeSecretFileAtomic(target, 'fresh')
assert.equal(modeOf(target), SECRET_FILE_MODE)
assert.equal(fs.readFileSync(target, 'utf8'), 'fresh')
})
}
)
/**
* Owner-only is carried by two independent mechanisms — the create-time `mode`
* and the chmod before the rename — because each covers a case the other
* cannot. The next two tests knock out one mechanism at a time (with the REAL
* fs doing the actual write, so the assertion is still the on-disk mode) and
* require the survivor to hold the line on its own. Without them, either
* mechanism could be deleted with every test still green.
*/
function fsWith(overrides: Record<string, unknown>) {
return { ...fs, ...overrides } as any
}
test.runIf(process.platform !== 'win32')('the written file is owner-only even where chmod does nothing', () => {
// A POSIX filesystem where chmod is unavailable. The create-time `mode` is what
// covers this — there is no second chance to tighten.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
// Pin a permissive umask so a mode-less create WOULD land
// group/other-readable — otherwise a restrictive-umask host could pass this
// for free. Synchronous and restored in `finally`, and the electron project
// runs one process per file, so no other test observes it.
const previousUmask = process.umask(0o022)
try {
const witness = path.join(dir, 'witness.json')
fs.writeFileSync(witness, 'x')
assert.notEqual(modeOf(witness), SECRET_FILE_MODE, 'the ambient default is NOT already owner-only')
writeSecretFileAtomic(target, 'tok', { fs: fsWith({ chmodSync: () => void 0 }) })
} finally {
process.umask(previousUmask)
}
assert.equal(modeOf(target), SECRET_FILE_MODE, 'created owner-only, not tightened after the fact')
})
})
test.runIf(process.platform !== 'win32')(
'the written file is owner-only even when a stale temp cannot be removed',
() => {
// The unlink is best-effort; if the stale temp survives, writeFileSync's
// `mode` is ignored on an existing path and only the chmod before the rename
// can still fix the bits.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
fs.writeFileSync(`${target}.tmp`, 'stale', { mode: 0o666 })
writeSecretFileAtomic(target, 'tok', { fs: fsWith({ rmSync: () => void 0 }) })
assert.equal(modeOf(target), SECRET_FILE_MODE, 'tightened before the rename handed the bits over')
assert.equal(fs.readFileSync(target, 'utf8'), 'tok')
})
}
)
test('writeSecretFileAtomic cannot be redirected through a symlink planted at the temp path', context => {
// A stale temp path is attacker-controllable in a shared temp/userData dir.
// Following it would write the token into the victim file AND then rename the
// link over connection.json, so every later write leaks too.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
const victim = path.join(dir, 'victim.txt')
fs.writeFileSync(victim, 'original', { mode: 0o644 })
const victimMode = modeOf(victim)
try {
fs.symlinkSync(victim, `${target}.tmp`, 'file')
} catch (error: any) {
if (error?.code === 'EPERM' || error?.code === 'EACCES') {
context.skip('creating a file symlink requires host permission')
}
throw error
}
writeSecretFileAtomic(target, 'tok-live-42')
assert.equal(fs.readFileSync(victim, 'utf8'), 'original', 'the symlink target was not written through')
assert.equal(modeOf(victim), victimMode, 'the victim file mode stays unchanged')
assert.equal(fs.readFileSync(target, 'utf8'), 'tok-live-42')
assert.equal(fs.lstatSync(target).isSymbolicLink(), false, 'the target is a real file, not the planted link')
if (process.platform !== 'win32') {
assert.equal(modeOf(target), SECRET_FILE_MODE)
}
})
})
test.runIf(process.platform !== 'win32')(
'tightenSecretFileMode tightens a pre-existing world-readable config in place',
() => {
// The upgrade path: a connection.json written by an older build sits at 0644
// with a real (encrypted) token in it. Tightening must change the mode and
// nothing else — the token has to stay readable or the user loses their
// configured gateway.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
const legacy = JSON.stringify({
mode: 'remote',
remote: {
url: 'https://gw.example.com',
authMode: 'token',
token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' }
}
})
fs.writeFileSync(target, legacy, { mode: 0o644 })
assert.equal(modeOf(target), 0o644)
assert.equal(tightenSecretFileMode(target), true)
assert.equal(modeOf(target), SECRET_FILE_MODE)
assert.deepEqual(JSON.parse(fs.readFileSync(target, 'utf8')), JSON.parse(legacy), 'contents untouched')
})
}
)
test.runIf(process.platform !== 'win32')(
'tightenSecretFileMode leaves a non-safeStorage token payload readable',
() => {
// A hand-edited config (or one from a pre-release build) can hold a
// non-safeStorage token payload, which decryptDesktopSecret still reads
// verbatim on purpose. Tightening the mode must not disturb that fallback —
// it only narrows who can open the file.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
const legacyPlain = JSON.stringify({
mode: 'remote',
remote: { url: 'https://gw.example.com', authMode: 'token', token: { encoding: 'plain', value: 'tok-live-42' } }
})
fs.writeFileSync(target, legacyPlain, { mode: 0o644 })
tightenSecretFileMode(target)
assert.equal(modeOf(target), SECRET_FILE_MODE)
assert.equal(JSON.parse(fs.readFileSync(target, 'utf8')).remote.token.value, 'tok-live-42')
})
}
)
test.runIf(process.platform !== 'win32')(
'tightenSecretFileMode is idempotent and never throws on an unusable path',
() => {
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
writeSecretFileAtomic(target, '{}')
assert.equal(tightenSecretFileMode(target), true)
assert.equal(tightenSecretFileMode(target), true)
assert.equal(modeOf(target), SECRET_FILE_MODE)
// Missing file (fresh install, nothing saved yet) reports failure quietly
// instead of breaking the read path it is called from.
assert.equal(tightenSecretFileMode(path.join(dir, 'absent.json')), false)
})
}
)
test('tightenSecretFileMode never changes a symlink target', context => {
// Matches readInstallationId in desktop-installation.ts. Without the lstat
// guard a link planted at the config path sends the chmod to whatever it
// resolves to — someone else's file gets its mode rewritten.
withTempDir(dir => {
const target = path.join(dir, 'connection.json')
const victim = path.join(dir, 'victim.txt')
fs.writeFileSync(victim, 'not mine', { mode: 0o644 })
const victimMode = modeOf(victim)
try {
fs.symlinkSync(victim, target, 'file')
} catch (error: any) {
if (error?.code === 'EPERM' || error?.code === 'EACCES') {
context.skip('creating a file symlink requires host permission')
}
throw error
}
assert.equal(tightenSecretFileMode(target), process.platform === 'win32')
assert.equal(modeOf(victim), victimMode, 'the symlink target keeps its own mode')
})
})
test.runIf(process.platform !== 'win32')(
'tightenSecretFileMode only touches a regular file the current user owns',
() => {
// Directories, sockets, fifos and files owned by another account are all
// "not ours to chmod". Injected lstat so the foreign-owner branch is
// reachable without a second OS account.
const chmodded: string[] = []
const fakeFs = (stat: Record<string, unknown>) =>
({
chmodSync: (filePath: string) => void chmodded.push(filePath),
lstatSync: () => ({ isFile: () => true, isSymbolicLink: () => false, mode: 0o644, uid: 0, ...stat }),
renameSync: () => void 0,
rmSync: () => void 0,
writeFileSync: () => void 0
}) as any
const uid = typeof process.getuid === 'function' ? process.getuid() : 0
assert.equal(
tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ isFile: () => false }), platform: 'linux' }),
false
)
assert.equal(
tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ uid: uid + 1 }), platform: 'linux' }),
false,
'a file owned by another user is left alone'
)
assert.deepEqual(chmodded, [], 'nothing was chmodded on the rejected paths')
// The same fs shape, but ours and loose: now it tightens.
assert.equal(tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ uid }), platform: 'linux' }), true)
assert.deepEqual(chmodded, ['/x/connection.json'])
}
)
test('tightenSecretFileMode leaves Windows alone rather than flipping the read-only bit', () => {
const chmods: string[] = []
const fakeFs = {
chmodSync: (filePath: string) => void chmods.push(filePath),
lstatSync: () => ({
isFile: () => true,
isSymbolicLink: () => false,
mode: 0o644,
uid: typeof process.getuid === 'function' ? process.getuid() : 0
}),
renameSync: () => void 0,
rmSync: () => void 0,
writeFileSync: () => void 0
} as any
assert.equal(tightenSecretFileMode('C:\\Users\\me\\connection.json', { fs: fakeFs, platform: 'win32' }), true)
assert.deepEqual(chmods, [], 'no chmod on win32')
// Same fs, POSIX: the chmod does happen, proving the platform gate is what
// suppressed it above.
assert.equal(tightenSecretFileMode('/home/me/connection.json', { fs: fakeFs, platform: 'linux' }), true)
assert.ok(chmods.includes('/home/me/connection.json'), 'the POSIX path was tightened')
})
test('a token is never persisted in plaintext when safeStorage is unavailable', () => {
// The defined degradation for `isEncryptionAvailable() === false` (Linux with
// no keyring): encryptDesktopSecret throws with an actionable message, so the
// save aborts before any write. It must never fall back to a plaintext
// payload — the file mode is defense in depth, not a substitute for the
// keychain.
const unavailable = {
isEncryptionAvailable: () => false,
encryptString: () => Buffer.from('unused', 'utf8')
}
assert.throws(
() => encryptDesktopSecret('tok-live-42', unavailable),
(error: unknown) => {
assert.ok(error instanceof Error, 'aborts instead of returning a payload')
assert.match(String((error as Error).message), /Secure token storage is unavailable/)
assert.doesNotMatch(String((error as Error).message), /tok-live-42/, 'the secret is not echoed in the error')
return true
}
)
// And a throwing keychain (available, but encryptString fails) is the same
// contract — no silent plaintext.
assert.throws(
() =>
encryptDesktopSecret('tok-live-42', {
isEncryptionAvailable: () => true,
encryptString: () => {
throw new Error('keyring locked')
}
}),
/Failed to encrypt the remote gateway token/
)
})
test('sensitiveFileBlockReason blocks obvious secret file patterns', () => {
assert.match(String(sensitiveFileBlockReason('/tmp/.env')), /\.env/)
assert.equal(sensitiveFileBlockReason('/tmp/.env.example'), null)
assert.match(String(sensitiveFileBlockReason('/Users/me/.ssh/id_ed25519')), /SSH/)
assert.match(String(sensitiveFileBlockReason('/tmp/server-cert.pem')), /\.pem/)
})
test('path helpers reject blank non-string NUL and Windows device syntax', async () => {
await rejectsWithCode(resolveReadableFileForIpc('', { purpose: 'File preview' }), 'invalid-path')
await rejectsWithCode(resolveReadableFileForIpc(' ', { purpose: 'File preview' }), 'invalid-path')
await rejectsWithCode(resolveReadableFileForIpc(null, { purpose: 'File preview' }), 'invalid-path')
await rejectsWithCode(resolveReadableFileForIpc(`safe${String.fromCharCode(0)}name.txt`), 'invalid-path')
const devicePaths = [
'\\\\?\\C:\\secret.txt',
'\\\\.\\C:\\secret.txt',
'\\\\?\\UNC\\server\\share\\secret.txt',
'GLOBALROOT/Device/HarddiskVolumeShadowCopy1/secret.txt'
]
for (const devicePath of devicePaths) {
assert.throws(
() => resolveRequestedPathForIpc(devicePath, { purpose: 'File preview' }),
(error: any) => {
assert.equal(error?.code, 'device-path')
return true
}
)
await rejectsWithCode(resolveReadableFileForIpc(devicePath, { purpose: 'File preview' }), 'device-path')
}
assert.throws(
() => resolveRequestedPathForIpc('file:///%E0%A4%A', { purpose: 'File preview' }),
(error: any) => {
assert.equal(error?.code, 'invalid-path')
return true
}
)
await rejectsWithCode(resolveReadableFileForIpc('file:///%E0%A4%A', { purpose: 'File preview' }), 'invalid-path')
})
test('resolveRequestedPathForIpc resolves relative paths from the trimmed base directory', () => {
const baseDir = path.join(os.tmpdir(), 'hermes-desktop-base')
assert.equal(
resolveRequestedPathForIpc('notes.txt', {
baseDir: ` ${baseDir} `,
purpose: 'File preview'
}),
path.resolve(baseDir, 'notes.txt')
)
})
test('resolveRequestedPathForIpc expands ~ to the home directory', () => {
assert.equal(resolveRequestedPathForIpc('~', { purpose: 'Directory read' }), path.resolve(os.homedir()))
assert.equal(
resolveRequestedPathForIpc('~/www/project', { purpose: 'Directory read' }),
path.resolve(os.homedir(), 'www/project')
)
// `~user` shorthand is NOT expanded — only the caller's own home.
assert.equal(
resolveRequestedPathForIpc('~other/secret', { baseDir: os.tmpdir(), purpose: 'Directory read' }),
path.resolve(os.tmpdir(), '~other/secret')
)
})
test('resolveReadableFileForIpc validates existence type size and sensitivity', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-hardening-'))
try {
const textPath = path.join(tempDir, 'notes.txt')
fs.writeFileSync(textPath, 'hello world', 'utf8')
const fromRelative = await resolveReadableFileForIpc('notes.txt', {
baseDir: tempDir,
maxBytes: 256,
purpose: 'File preview'
})
assert.equal(fromRelative.resolvedPath, textPath)
assert.equal(fromRelative.stat.size, 11)
const fromFileUrl = await resolveReadableFileForIpc(pathToFileURL(textPath).toString(), {
purpose: 'File preview'
})
assert.equal(fromFileUrl.resolvedPath, textPath)
const spacedPath = path.join(tempDir, 'notes with spaces.txt')
fs.writeFileSync(spacedPath, 'space ok', 'utf8')
const fromSpacedFileUrl = await resolveReadableFileForIpc(pathToFileURL(spacedPath).toString(), {
purpose: 'File preview'
})
assert.equal(fromSpacedFileUrl.resolvedPath, spacedPath)
await assert.rejects(
resolveReadableFileForIpc('missing.txt', {
baseDir: tempDir,
purpose: 'Text preview'
}),
/file does not exist/
)
const nestedDir = path.join(tempDir, 'directory')
fs.mkdirSync(nestedDir)
await assert.rejects(
resolveReadableFileForIpc(nestedDir, {
purpose: 'Text preview'
}),
/path points to a directory/
)
const largePath = path.join(tempDir, 'large.txt')
fs.writeFileSync(largePath, 'x'.repeat(40), 'utf8')
await assert.rejects(
resolveReadableFileForIpc(largePath, {
maxBytes: 8,
purpose: 'File preview'
}),
/file is too large/
)
const envPath = path.join(tempDir, '.env')
fs.writeFileSync(envPath, 'SECRET_TOKEN=123', 'utf8')
await assert.rejects(
resolveReadableFileForIpc(envPath, {
purpose: 'File preview'
}),
/blocked for sensitive file/
)
const envTemplatePath = path.join(tempDir, '.env.example')
fs.writeFileSync(envTemplatePath, 'EXAMPLE_TOKEN=value', 'utf8')
const envTemplate = await resolveReadableFileForIpc(envTemplatePath, {
purpose: 'File preview'
})
assert.equal(envTemplate.resolvedPath, envTemplatePath)
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('resolveReadableFileForIpc blocks common sensitive files', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-sensitive-'))
try {
const sshDir = path.join(tempDir, '.ssh')
fs.mkdirSync(sshDir)
const blockedFiles = [
path.join(tempDir, '.env'),
path.join(tempDir, '.npmrc'),
path.join(sshDir, 'id_ed25519'),
path.join(tempDir, 'cert.pem'),
path.join(tempDir, 'cert.p12'),
path.join(tempDir, 'cert.pfx')
]
for (const filePath of blockedFiles) {
fs.writeFileSync(filePath, 'secret', 'utf8')
await rejectsWithCode(resolveReadableFileForIpc(filePath, { purpose: 'File preview' }), 'sensitive-file')
}
const allowed = path.join(tempDir, '.env.example')
fs.writeFileSync(allowed, 'EXAMPLE_TOKEN=value', 'utf8')
assert.equal((await resolveReadableFileForIpc(allowed, { purpose: 'File preview' })).resolvedPath, allowed)
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('resolveReadableFileForIpc blocks symlinks whose realpath is sensitive', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-realpath-'))
try {
const envPath = path.join(tempDir, '.env')
const linkPath = path.join(tempDir, 'safe-name.txt')
fs.writeFileSync(envPath, 'SECRET_TOKEN=123', 'utf8')
try {
fs.symlinkSync(envPath, linkPath, 'file')
} catch (error) {
if (error?.code === 'EPERM' || error?.code === 'EACCES') {
// symlink creation is not permitted on this platform — skip
return
}
throw error
}
await rejectsWithCode(resolveReadableFileForIpc(linkPath, { purpose: 'File preview' }), 'sensitive-file')
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('resolveDirectoryForIpc accepts directories and rejects invalid directory targets', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-dir-'))
try {
const directory = path.join(tempDir, 'project')
const filePath = path.join(tempDir, 'file.txt')
fs.mkdirSync(directory)
fs.writeFileSync(filePath, 'not a directory', 'utf8')
const resolved = await resolveDirectoryForIpc(directory)
assert.equal(resolved.resolvedPath, directory)
assert.equal(resolved.stat.isDirectory(), true)
await rejectsWithCode(resolveDirectoryForIpc(filePath), 'ENOTDIR')
await rejectsWithCode(resolveDirectoryForIpc(path.join(tempDir, 'missing')), 'ENOENT')
await rejectsWithCode(resolveDirectoryForIpc('\\\\?\\C:\\secret'), 'device-path')
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('resolveDirectoryForIpc accepts directory symlinks or junctions', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-dir-link-'))
try {
const directory = path.join(tempDir, 'actual-project')
const linkPath = path.join(tempDir, 'linked-project')
fs.mkdirSync(directory)
try {
fs.symlinkSync(directory, linkPath, process.platform === 'win32' ? 'junction' : 'dir')
} catch (error) {
if (error?.code === 'EPERM' || error?.code === 'EACCES') {
// directory symlink creation is not permitted on this platform — skip
return
}
throw error
}
const resolved = await resolveDirectoryForIpc(linkPath)
assert.equal(resolved.resolvedPath, linkPath)
assert.equal(resolved.stat.isDirectory(), true)
} finally {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
// ---------------------------------------------------------------------------
// homeRelativeAttachmentCandidates (#115609)
// ---------------------------------------------------------------------------
test('homeRelativeAttachmentCandidates tries the home dir and the HERMES_HOME attachments dir', () => {
const candidates = homeRelativeAttachmentCandidates(
'AppData/Local/hermes/attachments/foo.xlsx',
'/Users/alice',
'/Users/alice/AppData/Local/hermes'
)
assert.deepEqual(candidates, [
path.join('/Users/alice', 'AppData/Local/hermes/attachments/foo.xlsx'),
path.join('/Users/alice/AppData/Local/hermes', 'attachments', 'foo.xlsx')
])
})
test('homeRelativeAttachmentCandidates normalizes Windows backslashes before joining', () => {
const candidates = homeRelativeAttachmentCandidates(
'AppData\\Local\\hermes\\attachments\\foo.xlsx',
'/Users/alice',
'/Users/alice/.hermes'
)
assert.equal(candidates[0], path.join('/Users/alice', 'AppData/Local/hermes/attachments/foo.xlsx'))
})
test('homeRelativeAttachmentCandidates returns nothing for an absolute path', () => {
assert.deepEqual(
homeRelativeAttachmentCandidates('/already/absolute/foo.xlsx', '/Users/alice', '/Users/alice/.hermes'),
[]
)
})
test('homeRelativeAttachmentCandidates returns nothing for a file: URL', () => {
assert.deepEqual(
homeRelativeAttachmentCandidates('file:///already/resolved/foo.xlsx', '/Users/alice', '/Users/alice/.hermes'),
[]
)
})
test('homeRelativeAttachmentCandidates returns nothing for empty input', () => {
assert.deepEqual(homeRelativeAttachmentCandidates('', '/Users/alice', '/Users/alice/.hermes'), [])
assert.deepEqual(homeRelativeAttachmentCandidates(' ', '/Users/alice', '/Users/alice/.hermes'), [])
})
test('homeRelativeAttachmentCandidates second candidate falls back to basename only', () => {
// A ref that lost its directory prefix entirely still has a shot via the
// well-known attachments dir + basename, matching the reported repro shape.
const candidates = homeRelativeAttachmentCandidates('foo.xlsx', '/Users/alice', '/Users/alice/.hermes')
assert.deepEqual(candidates, [
path.join('/Users/alice', 'foo.xlsx'),
path.join('/Users/alice/.hermes', 'attachments', 'foo.xlsx')
])
})