sandbox-config.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import { isIP } from 'node:net';
  2. import {
  3. getDefaultSandboxSettings,
  4. normalizeSandboxSettings,
  5. type SandboxFilesystemModeName,
  6. } from './sandbox-settings.js';
  7. export type SandboxFilesystemPolicy =
  8. | { mode: 'read_only' }
  9. | { mode: 'workspace_write' }
  10. | { mode: 'delete_guard' }
  11. | { mode: 'full_access' };
  12. export type SandboxNetworkPolicy = { mode: 'deny' } | { mode: 'allow_all' };
  13. export type SandboxLocalAccess = 'open' | 'restricted';
  14. export interface SandboxConfig {
  15. enabled: boolean;
  16. filesystem: {
  17. policy: SandboxFilesystemPolicy;
  18. denyRead: string[];
  19. denyWrite: string[];
  20. };
  21. network: {
  22. policy: SandboxNetworkPolicy;
  23. deniedDomains: string[];
  24. };
  25. localAccess: SandboxLocalAccess;
  26. }
  27. export function getSandboxConfigDefaults(platform: NodeJS.Platform): SandboxConfig {
  28. const settings = getDefaultSandboxSettings(platform);
  29. return {
  30. enabled: settings.enabled,
  31. filesystem: {
  32. policy: { mode: settings.filesystemMode },
  33. denyRead: [],
  34. denyWrite: [],
  35. },
  36. network: {
  37. policy: { mode: 'allow_all' },
  38. deniedDomains: [],
  39. },
  40. localAccess: 'open',
  41. };
  42. }
  43. export const SANDBOX_CONFIG_DEFAULTS = getSandboxConfigDefaults(process.platform);
  44. const FILESYSTEM_MODES = new Set(['read_only', 'workspace_write', 'delete_guard', 'full_access']);
  45. const NETWORK_MODES = new Set(['deny', 'allow_all']);
  46. export function parseSandboxConfig(
  47. raw: unknown,
  48. platform: NodeJS.Platform = process.platform,
  49. ): SandboxConfig {
  50. const defaults = getSandboxConfigDefaults(platform);
  51. if (raw === undefined) return defaults;
  52. const root = strictRecord(raw, 'sandbox', ['enabled', 'filesystem', 'network', 'localAccess']);
  53. const filesystem =
  54. root.filesystem === undefined
  55. ? {}
  56. : strictRecord(root.filesystem, 'sandbox.filesystem', [
  57. 'policy',
  58. 'denyRead',
  59. 'denyWrite',
  60. // Legacy key: older releases persisted `allowGitConfig` when the
  61. // settings UI saved the full sandbox object. Git config writes are
  62. // now always allowed and the toggle no longer exists, so any
  63. // persisted value (including `false`) is deliberately ignored
  64. // instead of rejected.
  65. 'allowGitConfig',
  66. ]);
  67. const filesystemPolicy =
  68. filesystem.policy === undefined
  69. ? {}
  70. : strictRecord(filesystem.policy, 'sandbox.filesystem.policy', ['mode']);
  71. const network =
  72. root.network === undefined
  73. ? {}
  74. : strictRecord(root.network, 'sandbox.network', ['policy', 'deniedDomains']);
  75. const networkPolicy =
  76. network.policy === undefined
  77. ? {}
  78. : strictRecord(network.policy, 'sandbox.network.policy', ['mode']);
  79. const enabled =
  80. root.enabled === undefined ? defaults.enabled : booleanValue(root.enabled, 'sandbox.enabled');
  81. // If explicitly enabled without a level, use deletion protection and let the runtime reject unsupported platforms.
  82. const filesystemMode = filesystemPolicy.mode ?? (enabled ? 'delete_guard' : 'full_access');
  83. if (typeof filesystemMode !== 'string' || !FILESYSTEM_MODES.has(filesystemMode)) {
  84. throw new Error(`Invalid sandbox.filesystem.policy.mode "${String(filesystemMode)}"`);
  85. }
  86. const networkMode = networkPolicy.mode ?? defaults.network.policy.mode;
  87. if (typeof networkMode !== 'string' || !NETWORK_MODES.has(networkMode)) {
  88. throw new Error(`Invalid sandbox.network.policy.mode "${String(networkMode)}"`);
  89. }
  90. const deniedDomains =
  91. network.deniedDomains === undefined
  92. ? [...defaults.network.deniedDomains]
  93. : stringArray(network.deniedDomains, 'sandbox.network.deniedDomains');
  94. for (const pattern of deniedDomains) assertDeniedDomainPattern(pattern);
  95. const settings = normalizeSandboxSettings({
  96. enabled,
  97. filesystemMode: filesystemMode as SandboxFilesystemModeName,
  98. });
  99. return {
  100. enabled: settings.enabled,
  101. filesystem: {
  102. policy: { mode: settings.filesystemMode },
  103. denyRead:
  104. filesystem.denyRead === undefined
  105. ? [...defaults.filesystem.denyRead]
  106. : stringArray(filesystem.denyRead, 'sandbox.filesystem.denyRead'),
  107. denyWrite:
  108. filesystem.denyWrite === undefined
  109. ? [...defaults.filesystem.denyWrite]
  110. : stringArray(filesystem.denyWrite, 'sandbox.filesystem.denyWrite'),
  111. },
  112. // Legacy network settings (deny mode and deniedDomains blocklist) are supported only for reading:
  113. // after validation, normalize to unrestricted access. Desktop Sandbox no longer actively restricts networking.
  114. network: {
  115. policy: { mode: 'allow_all' },
  116. deniedDomains: [],
  117. },
  118. localAccess:
  119. root.localAccess === undefined
  120. ? defaults.localAccess
  121. : root.localAccess === 'open' || root.localAccess === 'restricted'
  122. ? root.localAccess
  123. : (() => {
  124. throw new Error(`Invalid sandbox.localAccess "${String(root.localAccess)}"`);
  125. })(),
  126. };
  127. }
  128. function strictRecord(
  129. value: unknown,
  130. path: string,
  131. allowedKeys: readonly string[],
  132. ): Record<string, unknown> {
  133. if (value == null || typeof value !== 'object' || Array.isArray(value)) {
  134. throw new Error(`Invalid ${path}: expected object`);
  135. }
  136. const record = value as Record<string, unknown>;
  137. const unknown = Object.keys(record).find((key) => !allowedKeys.includes(key));
  138. if (unknown) throw new Error(`Unknown ${path}.${unknown}`);
  139. return record;
  140. }
  141. function booleanValue(value: unknown, path: string): boolean {
  142. if (typeof value !== 'boolean') throw new Error(`Invalid ${path}: expected boolean`);
  143. return value;
  144. }
  145. function stringArray(value: unknown, path: string): string[] {
  146. if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
  147. throw new Error(`Invalid ${path}: expected string array`);
  148. }
  149. return [...value];
  150. }
  151. function assertDeniedDomainPattern(pattern: string): void {
  152. const reject = () => {
  153. throw new Error(`Invalid sandbox.network.deniedDomains entry "${pattern}"`);
  154. };
  155. const bracketedIpv6 = pattern.match(/^\[([^\]]+)\](?::(.+))?$/);
  156. if (bracketedIpv6) {
  157. if (isIP(bracketedIpv6[1] ?? '') !== 6) reject();
  158. assertPort(bracketedIpv6[2], pattern);
  159. return;
  160. }
  161. if ((pattern.match(/:/g) ?? []).length > 1) {
  162. reject();
  163. }
  164. const portSeparator = pattern.lastIndexOf(':');
  165. const host = portSeparator > -1 ? pattern.slice(0, portSeparator) : pattern;
  166. const port = portSeparator > -1 ? pattern.slice(portSeparator + 1) : undefined;
  167. assertPort(port, pattern);
  168. if (host === '*') return;
  169. if (!isValidDomainPattern(host)) reject();
  170. }
  171. function isValidDomainPattern(host: string): boolean {
  172. if (host.includes('://') || host.includes('/') || host.includes(':')) return false;
  173. if (host === 'localhost') return true;
  174. if (host.startsWith('*.')) {
  175. const domain = host.slice(2);
  176. const parts = domain.split('.');
  177. return parts.length >= 2 && parts.every((part) => part.length > 0);
  178. }
  179. if (host.includes('*')) return false;
  180. return host.includes('.') && !host.startsWith('.') && !host.endsWith('.');
  181. }
  182. function assertPort(port: string | undefined, pattern: string): void {
  183. if (port === undefined) return;
  184. const value = Number(port);
  185. if (!/^[1-9][0-9]{0,4}$/.test(port) || !Number.isInteger(value) || value > 65_535) {
  186. throw new Error(`Invalid sandbox.network.deniedDomains entry "${pattern}"`);
  187. }
  188. }