path-resolver.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import path from 'node:path';
  2. import type { PathValue, ShellFamily } from './permission-core.js';
  3. export type PermissionPathResolutionContext = {
  4. workingDirectory?: string;
  5. homeDir?: string;
  6. };
  7. /**
  8. * Resolve a literal path without applying the host process platform to a
  9. * Windows-shaped value. This keeps permission candidate generation safe when
  10. * a POSIX daemon inspects a Windows shell command.
  11. */
  12. export function resolvePermissionPath(
  13. raw: string,
  14. context: PermissionPathResolutionContext = {},
  15. shell: ShellFamily = 'unknown',
  16. ): PathValue {
  17. if (raw.includes('$') || raw.includes('`')) {
  18. return { raw, dynamic: true, resolution: 'environment' };
  19. }
  20. if (raw.includes('?') || raw.includes('*') || raw.includes('[')) {
  21. return { raw, dynamic: true, resolution: 'glob' };
  22. }
  23. const windowsAbsolute = /^[A-Za-z]:[\\/]/.test(raw) || raw.startsWith('\\\\');
  24. if (windowsAbsolute) {
  25. return {
  26. raw,
  27. resolved: path.win32.normalize(raw),
  28. dynamic: false,
  29. resolution: 'absolute',
  30. };
  31. }
  32. if (raw === '~' || raw.startsWith('~/')) {
  33. if (!context.homeDir) return { raw, dynamic: true, resolution: 'home' };
  34. return {
  35. raw,
  36. resolved: path.resolve(context.homeDir, raw === '~' ? '.' : raw.slice(2)),
  37. dynamic: false,
  38. resolution: 'home',
  39. };
  40. }
  41. if (path.isAbsolute(raw)) {
  42. return { raw, resolved: path.normalize(raw), dynamic: false, resolution: 'absolute' };
  43. }
  44. const windowsContext =
  45. shell === 'cmd' ||
  46. shell === 'powershell' ||
  47. /^[A-Za-z]:[\\/]/.test(context.workingDirectory ?? '');
  48. if (windowsContext && context.workingDirectory) {
  49. return {
  50. raw,
  51. resolved: path.win32.resolve(context.workingDirectory, raw),
  52. dynamic: false,
  53. resolution: 'relative',
  54. };
  55. }
  56. return {
  57. raw,
  58. ...(context.workingDirectory ? { resolved: path.resolve(context.workingDirectory, raw) } : {}),
  59. dynamic: false,
  60. resolution: 'relative',
  61. };
  62. }