runner-protocol.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /** Closed private transports shared by the native subprocess runner. */
  2. import {
  3. chmodSync,
  4. existsSync,
  5. lstatSync,
  6. mkdtempSync,
  7. readFileSync,
  8. rmdirSync,
  9. unlinkSync,
  10. writeFileSync,
  11. } from 'node:fs'
  12. import { tmpdir } from 'node:os'
  13. import { basename, dirname, isAbsolute, join } from 'node:path'
  14. /** Target state restored by the Linux bootstrap after systemd establishes the scope. */
  15. export interface LinuxLaunchRequest {
  16. cwd: string
  17. env: Record<string, string>
  18. }
  19. /** Bounded Node-shaped error fields allowed across a private runner boundary. */
  20. export interface SerializedRunnerError {
  21. name: string
  22. message: string
  23. code?: string
  24. syscall?: string
  25. path?: string
  26. }
  27. /** A Linux pre-exec failure published beside its consumed request. */
  28. export type LinuxStartupError =
  29. { type: 'error'; error: SerializedRunnerError }
  30. /** The only parent-to-runner start message on Windows. */
  31. export interface WindowsStartRequest {
  32. type: 'start'
  33. cwd: string
  34. env: Record<string, string>
  35. }
  36. /** The only parent-to-runner control message on Windows. */
  37. export interface WindowsTerminateRequest {
  38. type: 'terminate'
  39. }
  40. /** Exactly one direct-result branch is sent by a connected Windows runner. */
  41. export type WindowsRunnerResult =
  42. | { type: 'target-exit'; exitCode: number }
  43. | { type: 'error'; error: SerializedRunnerError }
  44. /** Private paths owned by one Linux ordinary or PTY spawn. */
  45. export interface LinuxLaunchFiles {
  46. directory: string
  47. requestPath: string
  48. startupErrorPath: string
  49. }
  50. function isRecord(value: unknown): value is Record<string, unknown> {
  51. return value !== null && typeof value === 'object' && !Array.isArray(value)
  52. }
  53. function hasExactKeys(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): boolean {
  54. const allowed = new Set([...required, ...optional])
  55. return required.every(key => Object.hasOwn(value, key))
  56. && Object.keys(value).every(key => allowed.has(key))
  57. }
  58. function isStringRecord(value: unknown): value is Record<string, string> {
  59. return isRecord(value) && Object.values(value).every(entry => typeof entry === 'string')
  60. }
  61. function isSerializedRunnerError(value: unknown): value is SerializedRunnerError {
  62. if (!isRecord(value) || !hasExactKeys(
  63. value,
  64. ['name', 'message'],
  65. ['code', 'syscall', 'path'],
  66. )) return false
  67. return typeof value.name === 'string'
  68. && typeof value.message === 'string'
  69. && (value.code === undefined || typeof value.code === 'string')
  70. && (value.syscall === undefined || typeof value.syscall === 'string')
  71. && (value.path === undefined || typeof value.path === 'string')
  72. }
  73. function parseErrorResult(value: Record<string, unknown>): LinuxStartupError {
  74. if (!hasExactKeys(value, ['type', 'error']) || !isSerializedRunnerError(value.error)) {
  75. throw new Error('subprocess runner emitted an invalid error result')
  76. }
  77. if (value.type !== 'error') {
  78. throw new Error('subprocess runner emitted an unknown error result')
  79. }
  80. return { type: 'error', error: value.error }
  81. }
  82. /**
  83. * Create a private 0700 directory and one complete 0600 launch request.
  84. * @param request - target cwd and complete environment for the bootstrap.
  85. * @returns private paths owned by this launch.
  86. */
  87. export function createLinuxLaunchFiles(request: LinuxLaunchRequest): LinuxLaunchFiles {
  88. const directory = mkdtempSync(join(tmpdir(), 'dsh-subprocess-launch-'))
  89. const files = {
  90. directory,
  91. requestPath: join(directory, 'launch-request.json'),
  92. startupErrorPath: join(directory, 'startup-error.json'),
  93. }
  94. try {
  95. chmodSync(directory, 0o700)
  96. writeFileSync(files.requestPath, JSON.stringify(request), { flag: 'wx', mode: 0o600 })
  97. return files
  98. } catch (error) {
  99. cleanupLinuxLaunchFiles(files)
  100. throw error
  101. }
  102. }
  103. /**
  104. * Derive the only permitted startup-error path from an absolute request locator.
  105. * @param requestPath - absolute path to the private launch-request file.
  106. * @returns validated sibling paths for this launch.
  107. */
  108. export function linuxLaunchFilesFromLocator(requestPath: string): LinuxLaunchFiles {
  109. if (!isAbsolute(requestPath) || basename(requestPath) !== 'launch-request.json') {
  110. throw new Error('subprocess runner received an invalid Linux launch-request locator')
  111. }
  112. const directory = dirname(requestPath)
  113. return { directory, requestPath, startupErrorPath: join(directory, 'startup-error.json') }
  114. }
  115. /**
  116. * Strictly read and remove a one-shot Linux launch request.
  117. * @param requestPath - private launch-request path to consume.
  118. * @returns validated target cwd and environment.
  119. */
  120. export function consumeLinuxLaunchRequest(requestPath: string): LinuxLaunchRequest {
  121. const text = readFileSync(requestPath, 'utf8')
  122. unlinkSync(requestPath)
  123. const value: unknown = JSON.parse(text)
  124. if (!isRecord(value) || !hasExactKeys(value, ['cwd', 'env'])
  125. || typeof value.cwd !== 'string' || !isStringRecord(value.env)) {
  126. throw new Error('subprocess runner received an invalid Linux launch request')
  127. }
  128. return { cwd: value.cwd, env: value.env }
  129. }
  130. /**
  131. * Publish one strict 0600 Linux pre-exec error.
  132. * @param files - private paths for this launch.
  133. * @param error - bounded spawn or runner failure to publish.
  134. */
  135. export function writeLinuxStartupError(files: LinuxLaunchFiles, error: LinuxStartupError): void {
  136. writeFileSync(files.startupErrorPath, JSON.stringify(error), { flag: 'wx', mode: 0o600 })
  137. }
  138. /**
  139. * Read the Linux pre-exec error, if the bootstrap published one.
  140. * @param path - expected startup-error path.
  141. * @returns the validated failure, or undefined when none was published.
  142. */
  143. export function readLinuxStartupError(path: string): LinuxStartupError | undefined {
  144. if (!existsSync(path)) return undefined
  145. const value: unknown = JSON.parse(readFileSync(path, 'utf8'))
  146. if (!isRecord(value)) throw new Error('subprocess runner emitted an invalid startup error')
  147. return parseErrorResult(value)
  148. }
  149. /**
  150. * Strictly parse the single Windows start message.
  151. * @param value - untrusted IPC payload.
  152. * @returns validated target start request.
  153. */
  154. export function parseWindowsStartRequest(value: unknown): WindowsStartRequest {
  155. if (!isRecord(value) || !hasExactKeys(value, ['type', 'cwd', 'env'])
  156. || value.type !== 'start' || typeof value.cwd !== 'string' || !isStringRecord(value.env)) {
  157. throw new Error('subprocess runner received an invalid Windows start request')
  158. }
  159. return { type: 'start', cwd: value.cwd, env: value.env }
  160. }
  161. /**
  162. * Return true only for the exact, payload-free Windows terminate control.
  163. * @param value - untrusted IPC payload.
  164. * @returns whether the payload is the exact terminate request.
  165. */
  166. export function isWindowsTerminateRequest(value: unknown): value is WindowsTerminateRequest {
  167. return isRecord(value) && hasExactKeys(value, ['type']) && value.type === 'terminate'
  168. }
  169. /**
  170. * Strictly parse one of the two Windows direct-result branches.
  171. * @param value - untrusted IPC payload.
  172. * @returns validated direct-result message.
  173. */
  174. export function parseWindowsRunnerResult(value: unknown): WindowsRunnerResult {
  175. if (!isRecord(value) || typeof value.type !== 'string') {
  176. throw new Error('subprocess runner emitted an invalid Windows result')
  177. }
  178. if (value.type === 'error') return parseErrorResult(value)
  179. if (value.type === 'target-exit') {
  180. const validExitCode = typeof value.exitCode === 'number'
  181. && Number.isSafeInteger(value.exitCode)
  182. && value.exitCode >= 0
  183. if (!hasExactKeys(value, ['type', 'exitCode']) || !validExitCode) {
  184. throw new Error('subprocess runner emitted an invalid target-exit result')
  185. }
  186. return {
  187. type: 'target-exit',
  188. exitCode: value.exitCode as number,
  189. }
  190. }
  191. throw new Error(`subprocess runner emitted an unknown Windows result: ${value.type}`)
  192. }
  193. /**
  194. * Convert an unknown failure into the bounded cross-process error record.
  195. * @param error - failure caught at the process boundary.
  196. * @returns bounded serializable error fields.
  197. */
  198. export function serializeRunnerError(error: unknown): SerializedRunnerError {
  199. const source = error instanceof Error ? error : new Error(String(error))
  200. const node = source as NodeJS.ErrnoException & { path?: string }
  201. return {
  202. name: source.name,
  203. message: source.message,
  204. ...typeof node.code === 'string' ? { code: node.code } : {},
  205. ...typeof node.syscall === 'string' ? { syscall: node.syscall } : {},
  206. ...typeof node.path === 'string' ? { path: node.path } : {},
  207. }
  208. }
  209. /**
  210. * Rebuild a Node-shaped Error from a strict runner record.
  211. * @param serialized - validated bounded error fields.
  212. * @returns reconstructed Error with supported Node fields.
  213. */
  214. export function deserializeRunnerError(serialized: SerializedRunnerError): Error {
  215. const error = new Error(serialized.message)
  216. error.name = serialized.name
  217. return Object.assign(error, {
  218. ...serialized.code === undefined ? {} : { code: serialized.code },
  219. ...serialized.syscall === undefined ? {} : { syscall: serialized.syscall },
  220. ...serialized.path === undefined ? {} : { path: serialized.path },
  221. })
  222. }
  223. /**
  224. * Best-effort removal of only the private paths created for this Linux spawn.
  225. * @param files - exact private paths owned by this launch.
  226. */
  227. export function cleanupLinuxLaunchFiles(files: LinuxLaunchFiles): void {
  228. try {
  229. if (lstatSync(files.directory).isSymbolicLink()) {
  230. unlinkSync(files.directory)
  231. return
  232. }
  233. for (const path of [
  234. files.requestPath,
  235. files.startupErrorPath,
  236. ]) {
  237. try { unlinkSync(path) } catch (error) {
  238. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  239. }
  240. }
  241. rmdirSync(files.directory)
  242. } catch {
  243. // Crash residue remains private and no later spawn reuses this directory.
  244. }
  245. }