@warlock.js/process 5.39.2 → 5.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"identity.mjs","names":[],"sources":["../../../../../../../packages/process/src/identity.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\n\nimport { guardianProof } from \"./guardian\";\nimport { portableIdentity, type Command } from \"./platform\";\n\nconst execute = promisify(execFile);\nexport async function executeCommand(command: Command): Promise<string> {\n const { stdout } = await execute(command.file, command.args, {\n env: { ...process.env, ...command.env },\n timeout: 5000,\n maxBuffer: 4 * 1024 * 1024,\n windowsHide: true,\n });\n return stdout;\n}\nexport const TOKEN_ENV = \"WARLOCK_PROCESS_TOKEN\";\nexport type Identity = { start: string; group: number; state: string; rss: number; token?: string };\n\nfunction statFields(stat: string): string[] {\n return stat\n .slice(stat.lastIndexOf(\")\") + 2)\n .trim()\n .split(/\\s+/);\n}\n\n/**\n * A task that is exiting has already released its memory map (stat field 23,\n * vsize, reads 0) before it turns into a zombie. Linux then reports its /proc\n * files as root-owned, so it is never a live child to verify or signal.\n */\nfunction exiting(fields: string[]): boolean {\n return [\"Z\", \"X\"].includes(fields[0] ?? \"\") || fields[20] === \"0\";\n}\n\n/** /proc fields: https://man7.org/linux/man-pages/man5/proc_pid_stat.5.html */\nexport async function identity(\n pid: number,\n token = false,\n expectedToken?: string,\n): Promise<Identity | undefined> {\n if (!Number.isSafeInteger(pid) || pid <= 1) return undefined;\n try {\n if (process.platform === \"linux\") {\n const stat = await readFile(`/proc/${pid}/stat`, \"utf8\");\n const fields = statFields(stat);\n const state = fields[0];\n const start = fields[19];\n if (!state || !start || exiting(fields)) return undefined;\n const boot = (await readFile(\"/proc/sys/kernel/random/boot_id\", \"utf8\")).trim();\n const status = await readFile(`/proc/${pid}/status`, \"utf8\");\n let environment = \"\";\n if (token) {\n try {\n environment = await readFile(`/proc/${pid}/environ`, \"utf8\");\n } catch (error) {\n // Without root, the environment of a task that started exiting after\n // the first stat read is unreadable. Only that case counts as gone;\n // any other unreadable environment still fails closed.\n if ((error as { code?: unknown }).code !== \"EACCES\") throw error;\n const now = statFields(await readFile(`/proc/${pid}/stat`, \"utf8\"));\n if (now[19] !== start || exiting(now)) return undefined;\n throw error;\n }\n }\n // /proc reads are separate operations. Reject PID reuse or a group change\n // during observation before combining a token with a start identity.\n const after = statFields(await readFile(`/proc/${pid}/stat`, \"utf8\"));\n if (after[19] !== start || after[2] !== fields[2] || exiting(after)) return undefined;\n return {\n start: `${boot}:${start}`,\n group: Number(fields[2]),\n state: after[0] ?? state,\n rss: Number(/^VmRSS:\\s+(\\d+)/m.exec(status)?.[1] ?? 0) * 1024,\n token: environment\n .split(\"\\0\")\n .find((entry) => entry.startsWith(`${TOKEN_ENV}=`))\n ?.slice(TOKEN_ENV.length + 1),\n };\n }\n if (process.platform === \"darwin\" || process.platform === \"win32\")\n return await portableIdentity(process.platform, pid, token, executeCommand, (selected) =>\n guardianProof(selected, undefined, expectedToken),\n );\n return undefined;\n } catch (error) {\n const code = (error as { code?: unknown }).code;\n if (\n (process.platform === \"linux\" && [\"ENOENT\", \"ESRCH\"].includes(String(code))) ||\n (process.platform === \"darwin\" &&\n code === 1 &&\n !(error as { stdout?: string }).stdout?.trim())\n )\n return undefined;\n throw error;\n }\n}\n\nexport class ProcessNotOwnedError extends Error {\n constructor(public readonly pid: number) {\n super(`Process ${pid} does not have a verified supervisor identity`);\n this.name = \"ProcessNotOwnedError\";\n }\n}\n\nexport async function owns(entry: { pid: number; start: string; token: string }): Promise<boolean> {\n const current = await identity(entry.pid, true, entry.token);\n return (\n current?.start === entry.start && current.token === entry.token && current.group === entry.pid\n );\n}\n"],"mappings":";;;;;;;AAOA,MAAM,UAAU,UAAU,QAAQ;AAClC,eAAsB,eAAe,SAAmC;CACtE,MAAM,EAAE,WAAW,MAAM,QAAQ,QAAQ,MAA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,SAAS,MAAM,OAAO,OAAO,MAAM,QAAQ,KAAK,GAAG,OAAO;GAC5E,OAAO;IACL,OAAO,GAAG,KAAK,GAAG;IAClB,OAAO,OAAO,OAAO,EAAE;IACvB,OAAO,MAAM,MAAM;IACnB,KAAK,OAAO,mBAAmB,KAAK,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI;IACzD,OAAO,YACJ,MAAM,IAAI,CAAC,CACX,MAAM,UAAU,MAAM,WAAW,GAAG,UAAU,EAAE,CAAC,CAAC,EACjD,MAAM,EAAoB;GAChC;EACF;EACA,IAAI,QAAQ,aAAa,YAAY,QAAQ,aAAa,SACxD,OAAO,MAAM,iBAAiB,QAAQ,UAAU,KAAK,OAAO,iBAAiB,aAC3E,cAAc,UAAU,QAAW,aAAa,CAClD;EACF;CACF,SAAS,OAAO;EACd,MAAM,OAAQ,MAA6B;EAC3C,IACG,QAAQ,aAAa,WAAW,CAAC,UAAU,OAAO,CAAC,CAAC,SAAS,OAAO,IAAI,CAAC,KACzE,QAAQ,aAAa,YACpB,SAAS,KACT,CAAE,MAA8B,QAAQ,KAAK,GAE/C,OAAO;EACT,MAAM;CACR;AACF;AAEA,IAAa,uBAAb,cAA0C,MAAM;CAClB;CAA5B,YAAY,AAAgB,KAAa;EACvC,MAAM,WAAW,IAAI,8CAA8C;EADzC;EAE1B,KAAK,OAAO;CACd;AACF;AAEA,eAAsB,KAAK,OAAwE;CACjG,MAAM,UAAU,MAAM,SAAS,MAAM,KAAK,MAAM,MAAM,KAAK;CAC3D,OACE,SAAS,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM;AAE/F"}
1
+ {"version":3,"file":"identity.mjs","names":[],"sources":["../../../../../../../packages/process/src/identity.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\n\nimport { guardianProof } from \"./guardian\";\nimport { defaultObservationTimeoutMs, portableIdentity, type Command } from \"./platform\";\nimport type { WindowsProcessHelper } from \"./windows-helper\";\n\nconst execute = promisify(execFile);\nexport async function executeCommand(command: Command): Promise<string> {\n const { stdout } = await execute(command.file, command.args, {\n env: { ...process.env, ...command.env },\n timeout: 5000,\n maxBuffer: 4 * 1024 * 1024,\n windowsHide: true,\n });\n return stdout;\n}\n/** How a supervisor observes processes off Linux. Linux ignores all of it. */\nexport type Observation = {\n /** Longest wait for a guardian reply or a helper answer. */\n timeoutMs?: number;\n /** Long-lived Windows helper; without it each observation runs PowerShell once. */\n helper?: WindowsProcessHelper;\n /** Accept a process-table snapshot this old (polling only, never before a signal). */\n maxAgeMs?: number;\n};\nexport const TOKEN_ENV = \"WARLOCK_PROCESS_TOKEN\";\nexport type Identity = { start: string; group: number; state: string; rss: number; token?: string };\n\nfunction statFields(stat: string): string[] {\n return stat\n .slice(stat.lastIndexOf(\")\") + 2)\n .trim()\n .split(/\\s+/);\n}\n\n/**\n * A task that is exiting has already released its memory map (stat field 23,\n * vsize, reads 0) before it turns into a zombie. Linux then reports its /proc\n * files as root-owned, so it is never a live child to verify or signal.\n */\nfunction exiting(fields: string[]): boolean {\n return [\"Z\", \"X\"].includes(fields[0] ?? \"\") || fields[20] === \"0\";\n}\n\n/** /proc fields: https://man7.org/linux/man-pages/man5/proc_pid_stat.5.html */\nexport async function identity(\n pid: number,\n token = false,\n expectedToken?: string,\n observation: Observation = {},\n): Promise<Identity | undefined> {\n if (!Number.isSafeInteger(pid) || pid <= 1) return undefined;\n try {\n if (process.platform === \"linux\") {\n const stat = await readFile(`/proc/${pid}/stat`, \"utf8\");\n const fields = statFields(stat);\n const state = fields[0];\n const start = fields[19];\n if (!state || !start || exiting(fields)) return undefined;\n const boot = (await readFile(\"/proc/sys/kernel/random/boot_id\", \"utf8\")).trim();\n const status = await readFile(`/proc/${pid}/status`, \"utf8\");\n let environment = \"\";\n if (token) {\n try {\n environment = await readFile(`/proc/${pid}/environ`, \"utf8\");\n } catch (error) {\n // Without root, the environment of a task that started exiting after\n // the first stat read is unreadable. Only that case counts as gone;\n // any other unreadable environment still fails closed.\n if ((error as { code?: unknown }).code !== \"EACCES\") throw error;\n const now = statFields(await readFile(`/proc/${pid}/stat`, \"utf8\"));\n if (now[19] !== start || exiting(now)) return undefined;\n throw error;\n }\n }\n // /proc reads are separate operations. Reject PID reuse or a group change\n // during observation before combining a token with a start identity.\n const after = statFields(await readFile(`/proc/${pid}/stat`, \"utf8\"));\n if (after[19] !== start || after[2] !== fields[2] || exiting(after)) return undefined;\n return {\n start: `${boot}:${start}`,\n group: Number(fields[2]),\n state: after[0] ?? state,\n rss: Number(/^VmRSS:\\s+(\\d+)/m.exec(status)?.[1] ?? 0) * 1024,\n token: environment\n .split(\"\\0\")\n .find((entry) => entry.startsWith(`${TOKEN_ENV}=`))\n ?.slice(TOKEN_ENV.length + 1),\n };\n }\n if (process.platform === \"darwin\" || process.platform === \"win32\") {\n const { helper } = observation;\n return await portableIdentity(\n process.platform,\n pid,\n token,\n executeCommand,\n (selected) =>\n guardianProof(\n selected,\n undefined,\n expectedToken,\n observation.timeoutMs ?? defaultObservationTimeoutMs(process.platform),\n ),\n process.platform === \"win32\" && helper\n ? (pids, tree, maxAgeMs) => helper.query(pids, tree, maxAgeMs)\n : undefined,\n observation.maxAgeMs,\n );\n }\n return undefined;\n } catch (error) {\n const code = (error as { code?: unknown }).code;\n if (\n (process.platform === \"linux\" && [\"ENOENT\", \"ESRCH\"].includes(String(code))) ||\n (process.platform === \"darwin\" &&\n code === 1 &&\n !(error as { stdout?: string }).stdout?.trim())\n )\n return undefined;\n throw error;\n }\n}\n\nexport class ProcessNotOwnedError extends Error {\n constructor(public readonly pid: number) {\n super(`Process ${pid} does not have a verified supervisor identity`);\n this.name = \"ProcessNotOwnedError\";\n }\n}\n\nexport async function owns(\n entry: { pid: number; start: string; token: string },\n observation?: Observation,\n): Promise<boolean> {\n const current = await identity(entry.pid, true, entry.token, observation);\n return (\n current?.start === entry.start && current.token === entry.token && current.group === entry.pid\n );\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AM,OAAO,WAAW;CACxE,OACE,SAAS,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM;AAE/F"}
@@ -1 +1 @@
1
- {"version":3,"file":"platform.d.mts","names":[],"sources":["../../../../../../../packages/process/src/platform.ts"],"mappings":";qBAgBa,wCAAwC;WACvB;EAA5B,YAA4B"}
1
+ {"version":3,"file":"platform.d.mts","names":[],"sources":["../../../../../../../packages/process/src/platform.ts"],"mappings":";qBA6Ba,wCAAwC;WACvB;EAA5B,YAA4B"}
package/esm/platform.mjs CHANGED
@@ -1,4 +1,16 @@
1
1
  //#region ../../packages/process/src/platform.ts
2
+ /**
3
+ * Defaults per platform. Linux reads /proc directly, so it is cheap to poll
4
+ * often and a guardian reply is never awaited. Windows and macOS observe
5
+ * through helper programs and a named pipe, which need more time and a slower
6
+ * poll to stay out of the workload's way.
7
+ */
8
+ function defaultPollIntervalMs(platform) {
9
+ return platform === "win32" ? 1500 : platform === "darwin" ? 500 : 100;
10
+ }
11
+ function defaultObservationTimeoutMs(platform) {
12
+ return platform === "win32" || platform === "darwin" ? 15e3 : 2e3;
13
+ }
2
14
  var UnsupportedProcessPlatformError = class extends Error {
3
15
  platform;
4
16
  constructor(platform) {
@@ -87,7 +99,10 @@ function windowsCommand(pid, tree = false) {
87
99
  };
88
100
  }
89
101
  function parseWindowsRows(source) {
90
- const value = JSON.parse(source.replace(/^\uFEFF/, ""));
102
+ return windowsRows(JSON.parse(source.replace(/^\uFEFF/, "")));
103
+ }
104
+ /** Validates rows decoded from PowerShell, whether one-shot or from the long-lived helper. */
105
+ function windowsRows(value) {
91
106
  if (!Array.isArray(value)) throw new Error("Invalid Windows process observation");
92
107
  return value.map((row) => {
93
108
  if (!row || typeof row !== "object" || !("pid" in row) || typeof row.pid !== "number" || !Number.isSafeInteger(row.pid) || row.pid < 0 || !("parent" in row) || typeof row.parent !== "number" || !Number.isSafeInteger(row.parent) || row.parent < 0 || !("start" in row) || typeof row.start !== "string" || !/^\d{18}$/.test(row.start) || !("rss" in row) || typeof row.rss !== "number" || !Number.isFinite(row.rss) || row.rss < 0) throw new Error("Invalid Windows process observation");
@@ -131,16 +146,17 @@ function treeMemory(rows, pid) {
131
146
  return [...included.values()].reduce((total, row) => total + row.rss, 0);
132
147
  }
133
148
  /** All OS effects are injected; foreign-platform specs never execute real commands. */
134
- async function portableIdentity(platform, pid, token, execute, readProof) {
149
+ async function portableIdentity(platform, pid, token, execute, readProof, source, maxAgeMs = 0) {
135
150
  validPid(pid);
136
151
  const command = platform === "darwin" ? darwinCommand : windowsCommand;
137
152
  const parse = platform === "darwin" ? parseDarwinRows : parseWindowsRows;
138
- const rows = parse(await execute(command(pid, token)));
153
+ const read = source ?? (async (pids, tree) => parse(await execute(command(pids[0] ?? pid, tree))));
154
+ const rows = await read([pid], token, maxAgeMs);
139
155
  const before = rows.find((row) => row.pid === pid);
140
156
  if (!before || /^[ZX]/.test(before.state)) return void 0;
141
157
  if (!token) return before;
142
158
  const proof = await readProof(pid);
143
- const after = parse(await execute(command(pid))).find((row) => row.pid === pid);
159
+ const after = (await read([pid], false, maxAgeMs)).find((row) => row.pid === pid);
144
160
  if (!after || after.start !== before.start || after.group !== before.group || /^[ZX]/.test(after.state)) return void 0;
145
161
  return {
146
162
  start: after.start,
@@ -152,5 +168,5 @@ async function portableIdentity(platform, pid, token, execute, readProof) {
152
168
  }
153
169
 
154
170
  //#endregion
155
- export { UnsupportedProcessPlatformError, darwinCommand, parseDarwinRows, parseDarwinStart, parseWindowsRows, portableIdentity, supported, taskkillCommand, treeMemory, windowsCommand };
171
+ export { UnsupportedProcessPlatformError, darwinCommand, defaultObservationTimeoutMs, defaultPollIntervalMs, parseDarwinRows, parseDarwinStart, parseWindowsRows, portableIdentity, supported, taskkillCommand, treeMemory, windowsCommand, windowsRows };
156
172
  //# sourceMappingURL=platform.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"platform.mjs","names":[],"sources":["../../../../../../../packages/process/src/platform.ts"],"sourcesContent":["import type { Identity } from \"./identity\";\n\nexport type PortablePlatform = \"darwin\" | \"win32\";\nexport type Command = { file: string; args: string[]; env?: Record<string, string> };\nexport type Execute = (command: Command) => Promise<string>;\nexport type OwnershipProof = { pid: number; token: string; gated: boolean };\nexport type ReadProof = (pid: number) => Promise<OwnershipProof | undefined>;\ntype Row = {\n pid: number;\n parent: number;\n start: string;\n rss: number;\n group: number;\n state: string;\n};\n\nexport class UnsupportedProcessPlatformError extends Error {\n constructor(public readonly platform: string) {\n super(`Process supervision is unsupported on ${platform}`);\n this.name = \"UnsupportedProcessPlatformError\";\n }\n}\nexport function supported(platform: string): void {\n if (![\"linux\", \"darwin\", \"win32\"].includes(platform))\n throw new UnsupportedProcessPlatformError(platform);\n}\nfunction validPid(pid: number): void {\n if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error(\"Invalid process PID\");\n}\n\n/** Apple ps(1): lstart uses strftime %c. LC_ALL=C gives %a %b %e %H:%M:%S %Y.\n * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/ps.1\n * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/print.c (lstarted)\n * https://github.com/apple-oss-distributions/Libc/blob/main/stdtime/FreeBSD/timelocal.c (_C_time_locale)\n */\nexport function parseDarwinStart(source: string): string {\n const match =\n /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+(\\d{1,2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$/.exec(\n source.trim(),\n );\n if (!match) throw new Error(\"Invalid macOS process start time\");\n const [, weekday, month, day, hour, minute, second, year] = match;\n const monthIndex = \"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\"\n .split(\" \")\n .indexOf(month ?? \"\");\n const date = new Date(\n Date.UTC(Number(year), monthIndex, Number(day), Number(hour), Number(minute), Number(second)),\n );\n if (\n date.getUTCFullYear() !== Number(year) ||\n date.getUTCMonth() !== monthIndex ||\n date.getUTCDate() !== Number(day) ||\n date.getUTCHours() !== Number(hour) ||\n date.getUTCMinutes() !== Number(minute) ||\n date.getUTCSeconds() !== Number(second) ||\n \"Sun Mon Tue Wed Thu Fri Sat\".split(\" \")[date.getUTCDay()] !== weekday\n )\n throw new Error(\"Invalid macOS process start time\");\n return String(date.getTime() / 1000);\n}\nexport function darwinCommand(pid: number, tree = false): Command {\n validPid(pid);\n return {\n file: \"/bin/ps\",\n args: [...(tree ? [\"-ax\"] : [\"-p\", String(pid)]), \"-o\", \"pid=,ppid=,pgid=,state=,rss=,lstart=\"],\n env: { LC_ALL: \"C\", TZ: \"UTC\" },\n };\n}\nexport function parseDarwinRows(source: string): Row[] {\n return source.trim()\n ? source\n .trim()\n .split(\"\\n\")\n .map((line) => {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\d+)\\s+(.+?)\\s*$/.exec(line);\n if (!match) throw new Error(\"Invalid macOS process observation\");\n return {\n pid: Number(match[1]),\n parent: Number(match[2]),\n group: Number(match[3]),\n state: match[4] ?? \"\",\n rss: Number(match[5]) * 1024,\n start: parseDarwinStart(match[6] ?? \"\"),\n };\n })\n : [];\n}\n\n/** CIM CreationDate is a DateTime; serialize UTC ticks as text, never a locale date\n * or JSON number (100ns ticks exceed Number's precision). WorkingSetSize is bytes.\n * https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-process\n */\nexport function windowsCommand(pid: number, tree = false): Command {\n validPid(pid);\n const query = `Get-CimInstance Win32_Process${tree ? \"\" : ` -Filter 'ProcessId=${pid}'`}`;\n const script = [\n \"$ErrorActionPreference = 'Stop'\",\n `$rows = @(${query} | ForEach-Object {`,\n `if ([int]$_.ProcessId -eq ${pid} -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }`,\n \"if ($null -ne $_.CreationDate) {\",\n \"[pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }\",\n \"}\",\n \"})\",\n \"ConvertTo-Json -InputObject $rows -Compress\",\n ].join(\"\\n\");\n return {\n file: \"powershell.exe\",\n args: [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\", script],\n };\n}\nexport function parseWindowsRows(source: string): Row[] {\n const value: unknown = JSON.parse(source.replace(/^\\uFEFF/, \"\"));\n if (!Array.isArray(value)) throw new Error(\"Invalid Windows process observation\");\n return value.map((row: unknown) => {\n if (\n !row ||\n typeof row !== \"object\" ||\n !(\"pid\" in row) ||\n typeof row.pid !== \"number\" ||\n !Number.isSafeInteger(row.pid) ||\n row.pid < 0 ||\n !(\"parent\" in row) ||\n typeof row.parent !== \"number\" ||\n !Number.isSafeInteger(row.parent) ||\n row.parent < 0 ||\n !(\"start\" in row) ||\n typeof row.start !== \"string\" ||\n !/^\\d{18}$/.test(row.start) ||\n !(\"rss\" in row) ||\n typeof row.rss !== \"number\" ||\n !Number.isFinite(row.rss) ||\n row.rss < 0\n )\n throw new Error(\"Invalid Windows process observation\");\n return {\n pid: row.pid,\n parent: row.parent,\n start: row.start,\n rss: row.rss,\n group: row.pid,\n state: \"R\",\n };\n });\n}\nexport function taskkillCommand(pid: number): Command {\n validPid(pid);\n // Never accept an image name, filter, wildcard or shell interpolation.\n return { file: \"taskkill.exe\", args: [\"/PID\", String(pid), \"/T\", \"/F\"] };\n}\nexport function treeMemory(rows: Row[], pid: number): number {\n const root = rows.find((row) => row.pid === pid);\n if (!root) return 0;\n const included = new Map<number, Row>([[pid, root]]);\n let changed = true;\n while (changed) {\n changed = false;\n for (const row of rows) {\n const parent = included.get(row.parent);\n // Reject a reused parent PID whose creation time is later than the child.\n if (!included.has(row.pid) && parent && BigInt(row.start) >= BigInt(parent.start)) {\n included.set(row.pid, row);\n changed = true;\n }\n }\n }\n return [...included.values()].reduce((total, row) => total + row.rss, 0);\n}\n\n/** All OS effects are injected; foreign-platform specs never execute real commands. */\nexport async function portableIdentity(\n platform: PortablePlatform,\n pid: number,\n token: boolean,\n execute: Execute,\n readProof: ReadProof,\n): Promise<Identity | undefined> {\n validPid(pid);\n const command = platform === \"darwin\" ? darwinCommand : windowsCommand;\n const parse = platform === \"darwin\" ? parseDarwinRows : parseWindowsRows;\n const rows = parse(await execute(command(pid, token)));\n const before = rows.find((row) => row.pid === pid);\n if (!before || /^[ZX]/.test(before.state)) return undefined;\n if (!token) return before;\n const proof = await readProof(pid);\n const after = parse(await execute(command(pid))).find((row) => row.pid === pid);\n if (\n !after ||\n after.start !== before.start ||\n after.group !== before.group ||\n /^[ZX]/.test(after.state)\n )\n return undefined;\n return {\n start: after.start,\n group: after.group,\n state: proof?.pid === pid && proof.gated ? \"T\" : after.state,\n rss: treeMemory(rows, pid),\n token: proof?.pid === pid ? proof.token : undefined,\n };\n}\n"],"mappings":";AAgBA,IAAa,kCAAb,cAAqD,MAAM;CAC7B;CAA5B,YAAY,AAAgB,UAAkB;EAC5C,MAAM,yCAAyC,UAAU;EAD/B;EAE1B,KAAK,OAAO;CACd;AACF;AACA,SAAgB,UAAU,UAAwB;CAChD,IAAI,CAAC;EAAC;EAAS;EAAU;CAAO,CAAC,CAAC,SAAS,QAAQ,GACjD,MAAM,IAAI,gCAAgC,QAAQ;AACtD;AACA,SAAS,SAAS,KAAmB;CACnC,IAAI,CAAC,OAAO,cAAc,GAAG,KAAK,OAAO,GAAG,MAAM,IAAI,MAAM,qBAAqB;AACnF;;;;;;AAOA,SAAgB,iBAAiB,QAAwB;CACvD,MAAM,QACJ,gIAAgI,KAC9H,OAAO,KAAK,CACd;CACF,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,kCAAkC;CAC9D,MAAM,GAAG,SAAS,OAAO,KAAK,MAAM,QAAQ,QAAQ,QAAQ;CAC5D,MAAM,aAAa,kDAChB,MAAM,GAAG,CAAC,CACV,QAAQ,SAAS,EAAE;CACtB,MAAM,OAAO,I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
+ {"version":3,"file":"platform.mjs","names":[],"sources":["../../../../../../../packages/process/src/platform.ts"],"sourcesContent":["import type { Identity } from \"./identity\";\n\nexport type PortablePlatform = \"darwin\" | \"win32\";\nexport type Command = { file: string; args: string[]; env?: Record<string, string> };\nexport type Execute = (command: Command) => Promise<string>;\nexport type OwnershipProof = { pid: number; token: string; gated: boolean };\nexport type ReadProof = (pid: number) => Promise<OwnershipProof | undefined>;\nexport type Row = {\n pid: number;\n parent: number;\n start: string;\n rss: number;\n group: number;\n state: string;\n};\n\n/**\n * Defaults per platform. Linux reads /proc directly, so it is cheap to poll\n * often and a guardian reply is never awaited. Windows and macOS observe\n * through helper programs and a named pipe, which need more time and a slower\n * poll to stay out of the workload's way.\n */\nexport function defaultPollIntervalMs(platform: string): number {\n return platform === \"win32\" ? 1500 : platform === \"darwin\" ? 500 : 100;\n}\nexport function defaultObservationTimeoutMs(platform: string): number {\n return platform === \"win32\" || platform === \"darwin\" ? 15_000 : 2000;\n}\n\nexport class UnsupportedProcessPlatformError extends Error {\n constructor(public readonly platform: string) {\n super(`Process supervision is unsupported on ${platform}`);\n this.name = \"UnsupportedProcessPlatformError\";\n }\n}\nexport function supported(platform: string): void {\n if (![\"linux\", \"darwin\", \"win32\"].includes(platform))\n throw new UnsupportedProcessPlatformError(platform);\n}\nfunction validPid(pid: number): void {\n if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error(\"Invalid process PID\");\n}\n\n/** Apple ps(1): lstart uses strftime %c. LC_ALL=C gives %a %b %e %H:%M:%S %Y.\n * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/ps.1\n * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/print.c (lstarted)\n * https://github.com/apple-oss-distributions/Libc/blob/main/stdtime/FreeBSD/timelocal.c (_C_time_locale)\n */\nexport function parseDarwinStart(source: string): string {\n const match =\n /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+(\\d{1,2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$/.exec(\n source.trim(),\n );\n if (!match) throw new Error(\"Invalid macOS process start time\");\n const [, weekday, month, day, hour, minute, second, year] = match;\n const monthIndex = \"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\"\n .split(\" \")\n .indexOf(month ?? \"\");\n const date = new Date(\n Date.UTC(Number(year), monthIndex, Number(day), Number(hour), Number(minute), Number(second)),\n );\n if (\n date.getUTCFullYear() !== Number(year) ||\n date.getUTCMonth() !== monthIndex ||\n date.getUTCDate() !== Number(day) ||\n date.getUTCHours() !== Number(hour) ||\n date.getUTCMinutes() !== Number(minute) ||\n date.getUTCSeconds() !== Number(second) ||\n \"Sun Mon Tue Wed Thu Fri Sat\".split(\" \")[date.getUTCDay()] !== weekday\n )\n throw new Error(\"Invalid macOS process start time\");\n return String(date.getTime() / 1000);\n}\nexport function darwinCommand(pid: number, tree = false): Command {\n validPid(pid);\n return {\n file: \"/bin/ps\",\n args: [...(tree ? [\"-ax\"] : [\"-p\", String(pid)]), \"-o\", \"pid=,ppid=,pgid=,state=,rss=,lstart=\"],\n env: { LC_ALL: \"C\", TZ: \"UTC\" },\n };\n}\nexport function parseDarwinRows(source: string): Row[] {\n return source.trim()\n ? source\n .trim()\n .split(\"\\n\")\n .map((line) => {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\d+)\\s+(.+?)\\s*$/.exec(line);\n if (!match) throw new Error(\"Invalid macOS process observation\");\n return {\n pid: Number(match[1]),\n parent: Number(match[2]),\n group: Number(match[3]),\n state: match[4] ?? \"\",\n rss: Number(match[5]) * 1024,\n start: parseDarwinStart(match[6] ?? \"\"),\n };\n })\n : [];\n}\n\n/** CIM CreationDate is a DateTime; serialize UTC ticks as text, never a locale date\n * or JSON number (100ns ticks exceed Number's precision). WorkingSetSize is bytes.\n * https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-process\n */\nexport function windowsCommand(pid: number, tree = false): Command {\n validPid(pid);\n const query = `Get-CimInstance Win32_Process${tree ? \"\" : ` -Filter 'ProcessId=${pid}'`}`;\n const script = [\n \"$ErrorActionPreference = 'Stop'\",\n `$rows = @(${query} | ForEach-Object {`,\n `if ([int]$_.ProcessId -eq ${pid} -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }`,\n \"if ($null -ne $_.CreationDate) {\",\n \"[pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }\",\n \"}\",\n \"})\",\n \"ConvertTo-Json -InputObject $rows -Compress\",\n ].join(\"\\n\");\n return {\n file: \"powershell.exe\",\n args: [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-Command\", script],\n };\n}\nexport function parseWindowsRows(source: string): Row[] {\n return windowsRows(JSON.parse(source.replace(/^\\uFEFF/, \"\")));\n}\n/** Validates rows decoded from PowerShell, whether one-shot or from the long-lived helper. */\nexport function windowsRows(value: unknown): Row[] {\n if (!Array.isArray(value)) throw new Error(\"Invalid Windows process observation\");\n return value.map((row: unknown) => {\n if (\n !row ||\n typeof row !== \"object\" ||\n !(\"pid\" in row) ||\n typeof row.pid !== \"number\" ||\n !Number.isSafeInteger(row.pid) ||\n row.pid < 0 ||\n !(\"parent\" in row) ||\n typeof row.parent !== \"number\" ||\n !Number.isSafeInteger(row.parent) ||\n row.parent < 0 ||\n !(\"start\" in row) ||\n typeof row.start !== \"string\" ||\n !/^\\d{18}$/.test(row.start) ||\n !(\"rss\" in row) ||\n typeof row.rss !== \"number\" ||\n !Number.isFinite(row.rss) ||\n row.rss < 0\n )\n throw new Error(\"Invalid Windows process observation\");\n return {\n pid: row.pid,\n parent: row.parent,\n start: row.start,\n rss: row.rss,\n group: row.pid,\n state: \"R\",\n };\n });\n}\nexport function taskkillCommand(pid: number): Command {\n validPid(pid);\n // Never accept an image name, filter, wildcard or shell interpolation.\n return { file: \"taskkill.exe\", args: [\"/PID\", String(pid), \"/T\", \"/F\"] };\n}\nexport function treeMemory(rows: Row[], pid: number): number {\n const root = rows.find((row) => row.pid === pid);\n if (!root) return 0;\n const included = new Map<number, Row>([[pid, root]]);\n let changed = true;\n while (changed) {\n changed = false;\n for (const row of rows) {\n const parent = included.get(row.parent);\n // Reject a reused parent PID whose creation time is later than the child.\n if (!included.has(row.pid) && parent && BigInt(row.start) >= BigInt(parent.start)) {\n included.set(row.pid, row);\n changed = true;\n }\n }\n }\n return [...included.values()].reduce((total, row) => total + row.rss, 0);\n}\n\n/** Reads process rows. `tree` asks for the whole table; `maxAgeMs` accepts a recent snapshot. */\nexport type RowSource = (pids: number[], tree: boolean, maxAgeMs?: number) => Promise<Row[]>;\n\n/** All OS effects are injected; foreign-platform specs never execute real commands. */\nexport async function portableIdentity(\n platform: PortablePlatform,\n pid: number,\n token: boolean,\n execute: Execute,\n readProof: ReadProof,\n source?: RowSource,\n maxAgeMs = 0,\n): Promise<Identity | undefined> {\n validPid(pid);\n const command = platform === \"darwin\" ? darwinCommand : windowsCommand;\n const parse = platform === \"darwin\" ? parseDarwinRows : parseWindowsRows;\n const read: RowSource =\n source ?? (async (pids, tree) => parse(await execute(command(pids[0] ?? pid, tree))));\n const rows = await read([pid], token, maxAgeMs);\n const before = rows.find((row) => row.pid === pid);\n if (!before || /^[ZX]/.test(before.state)) return undefined;\n if (!token) return before;\n const proof = await readProof(pid);\n const after = (await read([pid], false, maxAgeMs)).find((row) => row.pid === pid);\n if (\n !after ||\n after.start !== before.start ||\n after.group !== before.group ||\n /^[ZX]/.test(after.state)\n )\n return undefined;\n return {\n start: after.start,\n group: after.group,\n state: proof?.pid === pid && proof.gated ? \"T\" : after.state,\n rss: treeMemory(rows, pid),\n token: proof?.pid === pid ? proof.token : undefined,\n };\n}\n"],"mappings":";;;;;;;AAsBA,SAAgB,sBAAsB,UAA0B;CAC9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I,KAAK,CAAC;AACzE;;AAMA,eAAsB,iBACpB,UACA,KACA,OACA,SACA,WACA,QACA,WAAW,GACoB;CAC/B,SAAS,GAAG;CACZ,MAAM,UAAU,aAAa,WAAW,gBAAgB;CACxD,MAAM,QAAQ,aAAa,WAAW,kBAAkB;CACxD,MAAM,OACJ,WAAW,OAAO,MAAM,SAAS,MAAM,MAAM,QAAQ,QAAQ,KAAK,MAAM,KAAK,IAAI,CAAC,CAAC;CACrF,MAAM,OAAO,MAAM,KAAK,CAAC,GAAG,GAAG,OAAO,QAAQ;CAC9C,MAAM,SAAS,KAAK,MAAM,QAAQ,IAAI,QAAQ,GAAG;CACjD,IAAI,CAAC,UAAU,QAAQ,KAAK,OAAO,KAAK,GAAG,OAAO;CAClD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,QAAQ,MAAM,UAAU,GAAG;CACjC,MAAM,SAAS,MAAM,KAAK,CAAC,GAAG,GAAG,OAAO,QAAQ,EAAC,CAAE,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAChF,IACE,CAAC,SACD,MAAM,UAAU,OAAO,SACvB,MAAM,UAAU,OAAO,SACvB,QAAQ,KAAK,MAAM,KAAK,GAExB,OAAO;CACT,OAAO;EACL,OAAO,MAAM;EACb,OAAO,MAAM;EACb,OAAO,OAAO,QAAQ,OAAO,MAAM,QAAQ,MAAM,MAAM;EACvD,KAAK,WAAW,MAAM,GAAG;EACzB,OAAO,OAAO,QAAQ,MAAM,MAAM,QAAQ;CAC5C;AACF"}
package/esm/registry.mjs CHANGED
@@ -34,18 +34,20 @@ function parseRegistry(source, owner) {
34
34
  var Registry = class {
35
35
  file;
36
36
  owner;
37
+ read;
37
38
  queue = Promise.resolve();
38
39
  locked = false;
39
- constructor(file, owner) {
40
+ constructor(file, owner, read = (pid) => identity(pid)) {
40
41
  this.file = file;
41
42
  this.owner = owner;
43
+ this.read = read;
42
44
  }
43
45
  async open() {
44
46
  await mkdir(path.dirname(this.file), {
45
47
  recursive: true,
46
48
  mode: 448
47
49
  });
48
- const self = await identity(process.pid);
50
+ const self = await this.read(process.pid);
49
51
  if (!self) throw new Error("Cannot verify registry writer identity");
50
52
  const lock = `${this.file}.lock`;
51
53
  try {
@@ -57,7 +59,7 @@ var Registry = class {
57
59
  try {
58
60
  const lease = JSON.parse(await readFile(path.join(lock, "writer.json"), "utf8"));
59
61
  if (!record(lease) || typeof lease.pid !== "number" || typeof lease.start !== "string") throw new Error("Invalid registry writer lease; inspect it manually");
60
- if ((await identity(lease.pid))?.start === lease.start) throw new Error("Process registry is already in use");
62
+ if ((await this.read(lease.pid))?.start === lease.start) throw new Error("Process registry is already in use");
61
63
  const stale = `${lock}.${randomBytes(8).toString("hex")}`;
62
64
  await rename(lock, stale);
63
65
  await rm(stale, { recursive: true });
@@ -1 +1 @@
1
- {"version":3,"file":"registry.mjs","names":[],"sources":["../../../../../../../packages/process/src/registry.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { identity } from \"./identity\";\nimport type { ProcessInfo } from \"./types\";\n\nexport type RegistryEntry = ProcessInfo & {\n token: string;\n start: string;\n cgroup?: string;\n /** Persisted launch gate: recovery may resume an adopted, interrupted launch. */\n gated?: boolean;\n};\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction strings(value: unknown): value is Record<string, string> {\n return record(value) && Object.values(value).every((item) => typeof item === \"string\");\n}\nexport function parseRegistry(source: string, owner: string): RegistryEntry[] {\n const value: unknown = JSON.parse(source);\n if (\n !record(value) ||\n value.version !== 1 ||\n value.owner !== owner ||\n !Array.isArray(value.entries)\n )\n throw new Error(\"Invalid process registry or different owner\");\n const entries: RegistryEntry[] = [];\n for (const entry of value.entries) {\n if (\n !record(entry) ||\n entry.owner !== owner ||\n typeof entry.pid !== \"number\" ||\n !Number.isSafeInteger(entry.pid) ||\n Number(entry.pid) <= 1 ||\n typeof entry.token !== \"string\" ||\n !/^[a-f0-9]{64}$/.test(entry.token) ||\n typeof entry.start !== \"string\" ||\n typeof entry.type !== \"string\" ||\n typeof entry.command !== \"string\" ||\n !Array.isArray(entry.args) ||\n !entry.args.every((arg) => typeof arg === \"string\") ||\n !strings(entry.labels) ||\n typeof entry.startedAt !== \"number\" ||\n !Number.isFinite(entry.startedAt) ||\n entry.startedAt < 0 ||\n !record(entry.limits) ||\n !Object.entries(entry.limits).every(\n ([key, limit]) =>\n [\"timeoutMs\", \"memoryBytes\", \"cpuSeconds\", \"virtualMemoryBytes\"].includes(key) &&\n typeof limit === \"number\" &&\n Number.isSafeInteger(limit) &&\n limit > 0,\n ) ||\n ![\"cgroup-v2\", \"rlimit-polling\", \"rss-polling\"].includes(String(entry.enforcement)) ||\n typeof entry.peakMemoryBytes !== \"number\" ||\n !Number.isFinite(entry.peakMemoryBytes) ||\n entry.peakMemoryBytes < 0 ||\n (entry.cgroup !== undefined && typeof entry.cgroup !== \"string\") ||\n (entry.gated !== undefined && typeof entry.gated !== \"boolean\")\n )\n throw new Error(\"Invalid process registry entry\");\n entries.push(entry as RegistryEntry);\n }\n if (new Set(entries.map((entry) => entry.pid)).size !== entries.length)\n throw new Error(\"Duplicate registry PID\");\n return entries;\n}\n\n/** One writer per registry. A crash leaves a lease which only a dead identity can release. */\nexport class Registry {\n private queue: Promise<void> = Promise.resolve();\n private locked = false;\n constructor(\n public readonly file: string,\n private readonly owner: string,\n ) {}\n async open(): Promise<RegistryEntry[]> {\n await mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });\n const self = await identity(process.pid);\n if (!self) throw new Error(\"Cannot verify registry writer identity\");\n const lock = `${this.file}.lock`;\n try {\n await mkdir(lock, { mode: 0o700 });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n const reclaim = `${lock}.reclaim`;\n await mkdir(reclaim, { mode: 0o700 });\n try {\n const lease: unknown = JSON.parse(await readFile(path.join(lock, \"writer.json\"), \"utf8\"));\n if (!record(lease) || typeof lease.pid !== \"number\" || typeof lease.start !== \"string\")\n throw new Error(\"Invalid registry writer lease; inspect it manually\");\n const writer = await identity(lease.pid);\n if (writer?.start === lease.start) throw new Error(\"Process registry is already in use\");\n const stale = `${lock}.${randomBytes(8).toString(\"hex\")}`;\n await rename(lock, stale);\n await rm(stale, { recursive: true });\n await mkdir(lock, { mode: 0o700 });\n } finally {\n await rm(reclaim, { recursive: true });\n }\n }\n this.locked = true;\n try {\n await writeFile(\n path.join(lock, \"writer.json\"),\n JSON.stringify({ pid: process.pid, start: self.start }),\n { mode: 0o600 },\n );\n try {\n return parseRegistry(await readFile(this.file, \"utf8\"), this.owner);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n } catch (error) {\n await this.close();\n throw error;\n }\n }\n save(entries: RegistryEntry[]): Promise<void> {\n const source = JSON.stringify({ version: 1, owner: this.owner, entries }, null, 2) + \"\\n\";\n const next = this.queue.then(async () => {\n const temporary = `${this.file}.${randomBytes(8).toString(\"hex\")}.tmp`;\n try {\n await writeFile(temporary, source, { mode: 0o600, flag: \"wx\" });\n await rename(temporary, this.file);\n } finally {\n await rm(temporary, { force: true });\n }\n });\n this.queue = next.catch(() => undefined);\n return next;\n }\n async close(): Promise<void> {\n await this.queue;\n if (this.locked) {\n await rm(`${this.file}.lock`, { recursive: true });\n this.locked = false;\n }\n }\n}\n"],"mappings":";;;;;;AAcA,SAAS,OAAO,OAAkD;CAChE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AACA,SAAS,QAAQ,OAAiD;CAChE,OAAO,OAAO,KAAK,KAAK,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,SAAS,OAAO,SAAS,QAAQ;AACvF;AACA,SAAgB,cAAc,QAAgB,OAAgC;CAC5E,MAAM,QAAiB,KAAK,MAAM,MAAM;CACxC,IACE,CAAC,OA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C;GACvC;EACF;EACA,KAAK,SAAS;EACd,IAAI;GACF,MAAM,UACJ,KAAK,KAAK,MAAM,aAAa,GAC7B,KAAK,UAAU;IAAE,KAAK,QAAQ;IAAK,OAAO,KAAK;GAAM,CAAC,GACtD,EAAE,MAAM,IAAM,CAChB;GACA,IAAI;IACF,OAAO,cAAc,MAAM,SAAS,KAAK,MAAM,MAAM,GAAG,KAAK,KAAK;GACpE,SAAS,OAAO;IACd,IAAK,MAAgC,SAAS,UAAU,OAAO,CAAC;IAChE,MAAM;GACR;EACF,SAAS,OAAO;GACd,MAAM,KAAK,MAAM;GACjB,MAAM;EACR;CACF;CACA,KAAK,SAAyC;EAC5C,MAAM,SAAS,KAAK,UAAU;GAAE,SAAS;GAAG,OAAO,KAAK;GAAO;EAAQ,GAAG,MAAM,CAAC,IAAI;EACrF,MAAM,OAAO,KAAK,MAAM,KAAK,YAAY;GACvC,MAAM,YAAY,GAAG,KAAK,KAAK,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;GACjE,IAAI;IACF,MAAM,UAAU,WAAW,QAAQ;KAAE,MAAM;KAAO,MAAM;IAAK,CAAC;IAC9D,MAAM,OAAO,WAAW,KAAK,IAAI;GACnC,UAAU;IACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;GACrC;EACF,CAAC;EACD,KAAK,QAAQ,KAAK,YAAY,MAAS;EACvC,OAAO;CACT;CACA,MAAM,QAAuB;EAC3B,MAAM,KAAK;EACX,IAAI,KAAK,QAAQ;GACf,MAAM,GAAG,GAAG,KAAK,KAAK,QAAQ,EAAE,WAAW,KAAK,CAAC;GACjD,KAAK,SAAS;EAChB;CACF;AACF"}
1
+ {"version":3,"file":"registry.mjs","names":[],"sources":["../../../../../../../packages/process/src/registry.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { identity } from \"./identity\";\nimport type { ProcessInfo } from \"./types\";\n\nexport type RegistryEntry = ProcessInfo & {\n token: string;\n start: string;\n cgroup?: string;\n /** Persisted launch gate: recovery may resume an adopted, interrupted launch. */\n gated?: boolean;\n};\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction strings(value: unknown): value is Record<string, string> {\n return record(value) && Object.values(value).every((item) => typeof item === \"string\");\n}\nexport function parseRegistry(source: string, owner: string): RegistryEntry[] {\n const value: unknown = JSON.parse(source);\n if (\n !record(value) ||\n value.version !== 1 ||\n value.owner !== owner ||\n !Array.isArray(value.entries)\n )\n throw new Error(\"Invalid process registry or different owner\");\n const entries: RegistryEntry[] = [];\n for (const entry of value.entries) {\n if (\n !record(entry) ||\n entry.owner !== owner ||\n typeof entry.pid !== \"number\" ||\n !Number.isSafeInteger(entry.pid) ||\n Number(entry.pid) <= 1 ||\n typeof entry.token !== \"string\" ||\n !/^[a-f0-9]{64}$/.test(entry.token) ||\n typeof entry.start !== \"string\" ||\n typeof entry.type !== \"string\" ||\n typeof entry.command !== \"string\" ||\n !Array.isArray(entry.args) ||\n !entry.args.every((arg) => typeof arg === \"string\") ||\n !strings(entry.labels) ||\n typeof entry.startedAt !== \"number\" ||\n !Number.isFinite(entry.startedAt) ||\n entry.startedAt < 0 ||\n !record(entry.limits) ||\n !Object.entries(entry.limits).every(\n ([key, limit]) =>\n [\"timeoutMs\", \"memoryBytes\", \"cpuSeconds\", \"virtualMemoryBytes\"].includes(key) &&\n typeof limit === \"number\" &&\n Number.isSafeInteger(limit) &&\n limit > 0,\n ) ||\n ![\"cgroup-v2\", \"rlimit-polling\", \"rss-polling\"].includes(String(entry.enforcement)) ||\n typeof entry.peakMemoryBytes !== \"number\" ||\n !Number.isFinite(entry.peakMemoryBytes) ||\n entry.peakMemoryBytes < 0 ||\n (entry.cgroup !== undefined && typeof entry.cgroup !== \"string\") ||\n (entry.gated !== undefined && typeof entry.gated !== \"boolean\")\n )\n throw new Error(\"Invalid process registry entry\");\n entries.push(entry as RegistryEntry);\n }\n if (new Set(entries.map((entry) => entry.pid)).size !== entries.length)\n throw new Error(\"Duplicate registry PID\");\n return entries;\n}\n\n/** One writer per registry. A crash leaves a lease which only a dead identity can release. */\nexport class Registry {\n private queue: Promise<void> = Promise.resolve();\n private locked = false;\n constructor(\n public readonly file: string,\n private readonly owner: string,\n private readonly read: (pid: number) => ReturnType<typeof identity> = (pid) => identity(pid),\n ) {}\n async open(): Promise<RegistryEntry[]> {\n await mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });\n const self = await this.read(process.pid);\n if (!self) throw new Error(\"Cannot verify registry writer identity\");\n const lock = `${this.file}.lock`;\n try {\n await mkdir(lock, { mode: 0o700 });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n const reclaim = `${lock}.reclaim`;\n await mkdir(reclaim, { mode: 0o700 });\n try {\n const lease: unknown = JSON.parse(await readFile(path.join(lock, \"writer.json\"), \"utf8\"));\n if (!record(lease) || typeof lease.pid !== \"number\" || typeof lease.start !== \"string\")\n throw new Error(\"Invalid registry writer lease; inspect it manually\");\n const writer = await this.read(lease.pid);\n if (writer?.start === lease.start) throw new Error(\"Process registry is already in use\");\n const stale = `${lock}.${randomBytes(8).toString(\"hex\")}`;\n await rename(lock, stale);\n await rm(stale, { recursive: true });\n await mkdir(lock, { mode: 0o700 });\n } finally {\n await rm(reclaim, { recursive: true });\n }\n }\n this.locked = true;\n try {\n await writeFile(\n path.join(lock, \"writer.json\"),\n JSON.stringify({ pid: process.pid, start: self.start }),\n { mode: 0o600 },\n );\n try {\n return parseRegistry(await readFile(this.file, \"utf8\"), this.owner);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n } catch (error) {\n await this.close();\n throw error;\n }\n }\n save(entries: RegistryEntry[]): Promise<void> {\n const source = JSON.stringify({ version: 1, owner: this.owner, entries }, null, 2) + \"\\n\";\n const next = this.queue.then(async () => {\n const temporary = `${this.file}.${randomBytes(8).toString(\"hex\")}.tmp`;\n try {\n await writeFile(temporary, source, { mode: 0o600, flag: \"wx\" });\n await rename(temporary, this.file);\n } finally {\n await rm(temporary, { force: true });\n }\n });\n this.queue = next.catch(() => undefined);\n return next;\n }\n async close(): Promise<void> {\n await this.queue;\n if (this.locked) {\n await rm(`${this.file}.lock`, { recursive: true });\n this.locked = false;\n }\n }\n}\n"],"mappings":";;;;;;AAcA,SAAS,OAAO,OAAkD;CAChE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AACA,SAAS,QAAQ,OAAiD;CAChE,OAAO,OAAO,KAAK,KAAK,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,SAAS,OAAO,SAAS,QAAQ;AACvF;AACA,SAAgB,cAAc,QAAgB,OAAgC;CAC5E,MAAM,QAAiB,KAAK,MAAM,MAAM;CACxC,IACE,CAAC,OAAO,KAAK,KACb,MAAM,YAAY,KAClB,MAAM,UAAU,SAChB,CAAC,MAAM,QAAQ,MAAM,OAAO,GAE5B,MAAM,IAAI,MAAM,6CAA6C;CAC/D,MAAM,UAA2B,CAAC;CAClC,KAAK,MAAM,SAAS,MAAM,SAAS;EACjC,IACE,CAAC,OAAO,KAAK,KACb,MAAM,UAAU,SAChB,OAAO,MAAM,QAAQ,YACrB,CAAC,OAAO,cAAc,MAAM,GAAG,KAC/B,OAAO,MAAM,GAAG,KAAK,KACrB,OAAO,MAAM,UAAU,YACvB,CAAC,iBAAiB,KAAK,MAAM,KAAK,KAClC,OAAO,MAAM,UAAU,YACvB,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,YAAY,YACzB,CAAC,MAAM,QAAQ,MAAM,IAAI,KACzB,CAAC,MAAM,KAAK,OAAO,QAAQ,OAAO,QAAQ,QAAQ,KAClD,CAAC,QAAQ,MAAM,MAAM,KACrB,OAAO,MAAM,cAAc,YAC3B,CAAC,OAAO,SAAS,MAAM,S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AAG,KAAK,KAAK,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;GACjE,IAAI;IACF,MAAM,UAAU,WAAW,QAAQ;KAAE,MAAM;KAAO,MAAM;IAAK,CAAC;IAC9D,MAAM,OAAO,WAAW,KAAK,IAAI;GACnC,UAAU;IACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;GACrC;EACF,CAAC;EACD,KAAK,QAAQ,KAAK,YAAY,MAAS;EACvC,OAAO;CACT;CACA,MAAM,QAAuB;EAC3B,MAAM,KAAK;EACX,IAAI,KAAK,QAAQ;GACf,MAAM,GAAG,GAAG,KAAK,KAAK,QAAQ,EAAE,WAAW,KAAK,CAAC;GACjD,KAAK,SAAS;EAChB;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"supervisor.d.mts","names":[],"sources":["../../../../../../../packages/process/src/supervisor.ts"],"mappings":";;wBAqFgB,WAAW,SAAS,oBAAoB"}
1
+ {"version":3,"file":"supervisor.d.mts","names":[],"sources":["../../../../../../../packages/process/src/supervisor.ts"],"mappings":";;wBA2FgB,WAAW,SAAS,oBAAoB"}
@@ -1,8 +1,9 @@
1
+ import { defaultObservationTimeoutMs, defaultPollIntervalMs, supported, taskkillCommand } from "./platform.mjs";
1
2
  import { attachCgroup, cgroupMemory, cleanCgroup, recoveredCgroup, validateLimits } from "./resources.mjs";
2
3
  import { guardianProof, launchCommand } from "./guardian.mjs";
3
- import { supported, taskkillCommand } from "./platform.mjs";
4
4
  import { ProcessNotOwnedError, executeCommand, identity, owns } from "./identity.mjs";
5
5
  import { Registry } from "./registry.mjs";
6
+ import { createWindowsHelper } from "./windows-helper.mjs";
6
7
  import { spawn } from "node:child_process";
7
8
  import { randomBytes } from "node:crypto";
8
9
  import path from "node:path";
@@ -28,10 +29,44 @@ function supervisor(options) {
28
29
  ...options,
29
30
  defaults: { ...options.defaults }
30
31
  };
31
- const pollMs = options.pollIntervalMs ?? 100;
32
+ const pollMs = options.pollIntervalMs ?? defaultPollIntervalMs(process.platform);
32
33
  const graceMs = options.stopGraceMs ?? 1e3;
33
34
  if (!Number.isSafeInteger(pollMs) || pollMs < 10 || !Number.isSafeInteger(graceMs) || graceMs < 0) throw new Error("Invalid polling interval or stop grace period");
34
- const registry = new Registry(path.resolve(options.registry), options.owner);
35
+ const registryPath = path.resolve(options.registry);
36
+ const sameProcess = sameProcessSupervisors();
37
+ const live = sameProcess.get(registryPath);
38
+ if (live && live.owner === options.owner) return live.api;
39
+ const observationMs = options.observationTimeoutMs ?? defaultObservationTimeoutMs(process.platform);
40
+ if (!Number.isSafeInteger(observationMs) || observationMs < 100) throw new Error("Invalid observationTimeoutMs: expected an integer of at least 100");
41
+ let helper;
42
+ function observe() {
43
+ if (process.platform === "win32") helper ??= createWindowsHelper({ timeoutMs: observationMs });
44
+ return {
45
+ timeoutMs: observationMs,
46
+ helper
47
+ };
48
+ }
49
+ /** Polling tolerates a snapshot up to one interval old; signals never do. */
50
+ function polling() {
51
+ return {
52
+ ...observe(),
53
+ maxAgeMs: pollMs
54
+ };
55
+ }
56
+ /**
57
+ * Registry lease checks read identities too. Off Linux they go through the shared
58
+ * helper, and a transient failure (an exiting process reports no creation time) is
59
+ * retried instead of failing the whole operation.
60
+ */
61
+ async function lease(pid) {
62
+ for (let attempt = 1;; attempt++) try {
63
+ return await identity(pid, false, void 0, observe());
64
+ } catch (error) {
65
+ if (process.platform === "linux" || attempt >= 3) throw error;
66
+ await setTimeout(200);
67
+ }
68
+ }
69
+ const registry = new Registry(registryPath, options.owner, lease);
35
70
  const entries = /* @__PURE__ */ new Map();
36
71
  const active = /* @__PURE__ */ new Map();
37
72
  let ready;
@@ -56,9 +91,9 @@ function supervisor(options) {
56
91
  }
57
92
  const save = () => registry.save([...entries.values()]);
58
93
  async function signal(entry, value) {
59
- if (!await owns(entry)) throw new ProcessNotOwnedError(entry.pid);
94
+ if (!await owns(entry, observe())) throw new ProcessNotOwnedError(entry.pid);
60
95
  if (process.platform !== "linux" && value === "SIGCONT") {
61
- const proof = await guardianProof(entry.pid, entry.token);
96
+ const proof = await guardianProof(entry.pid, entry.token, entry.token, observationMs);
62
97
  if (!proof || proof.token !== entry.token || proof.gated) throw new ProcessNotOwnedError(entry.pid);
63
98
  return;
64
99
  }
@@ -66,7 +101,7 @@ function supervisor(options) {
66
101
  try {
67
102
  await executeCommand(taskkillCommand(entry.pid));
68
103
  } catch (error) {
69
- if (await owns(entry)) throw error;
104
+ if (await owns(entry, observe())) throw error;
70
105
  }
71
106
  return;
72
107
  }
@@ -76,22 +111,48 @@ function supervisor(options) {
76
111
  if (error.code !== "ESRCH") throw error;
77
112
  }
78
113
  }
114
+ /**
115
+ * A process that is exiting can still be listed for a moment after its guardian
116
+ * (and so its token) is gone. Read fresh a few times; only a process that has
117
+ * disappeared counts as gone, and a live one keeps its not-owned failure.
118
+ */
119
+ async function gone(pid) {
120
+ for (let attempt = 0; attempt < 5; attempt++) {
121
+ if (!await identity(pid, false, void 0, observe())) return true;
122
+ await setTimeout(100);
123
+ }
124
+ return false;
125
+ }
126
+ /**
127
+ * Right after SIGCONT the launcher is replacing itself with the workload
128
+ * (exec). For that instant the kernel reports an empty memory map and
129
+ * environment, so a live, owned process momentarily fails verification. A
130
+ * handle returned by launch() must always be stoppable, so wait that window
131
+ * out; a process that stays unverified is still refused.
132
+ */
133
+ async function ownsSettled(entry) {
134
+ for (let attempt = 0; attempt < 25; attempt++) {
135
+ if (await owns(entry, observe())) return true;
136
+ await setTimeout(20);
137
+ }
138
+ return false;
139
+ }
79
140
  async function stopEntry(entry, reason = "stopped") {
80
141
  const tracked = active.get(entry.pid);
81
142
  let running;
82
143
  if (!tracked) {
83
- if (!await owns(entry)) throw new ProcessNotOwnedError(entry.pid);
144
+ if (!await owns(entry, observe())) throw new ProcessNotOwnedError(entry.pid);
84
145
  entry.cgroup = await recoveredCgroup(entry.pid, entry.token);
85
146
  running = track(entry);
86
147
  } else running = tracked;
87
148
  if (running.finished) return running.finish(null, null);
88
149
  if (running.stopping) return running.stopping;
89
150
  const stopping = (async () => {
90
- if (!await owns(entry)) throw new ProcessNotOwnedError(entry.pid);
151
+ if (!await ownsSettled(entry)) throw new ProcessNotOwnedError(entry.pid);
91
152
  running.reason ??= reason;
92
153
  await signal(entry, "SIGTERM");
93
154
  const deadline = Date.now() + graceMs;
94
- while (await owns(entry)) {
155
+ while (await owns(entry, observe())) {
95
156
  if (Date.now() >= deadline) {
96
157
  await signal(entry, "SIGKILL");
97
158
  break;
@@ -99,7 +160,7 @@ function supervisor(options) {
99
160
  await setTimeout(20);
100
161
  }
101
162
  const killedDeadline = Date.now() + 5e3;
102
- while (await owns(entry)) {
163
+ while (await owns(entry, observe())) {
103
164
  if (Date.now() >= killedDeadline) throw new Error(`Process ${entry.pid} did not exit after SIGKILL`);
104
165
  await setTimeout(20);
105
166
  }
@@ -110,7 +171,7 @@ function supervisor(options) {
110
171
  await stopping;
111
172
  } catch (error) {
112
173
  running.stopping = void 0;
113
- if (error instanceof ProcessNotOwnedError && !await identity(entry.pid)) {
174
+ if (error instanceof ProcessNotOwnedError && await gone(entry.pid)) {
114
175
  await running.finish(null, null);
115
176
  return;
116
177
  }
@@ -188,7 +249,13 @@ function supervisor(options) {
188
249
  sampling = true;
189
250
  try {
190
251
  const entry = running.entry;
191
- const current = await identity(entry.pid, true, entry.token);
252
+ let current = await identity(entry.pid, true, entry.token, polling());
253
+ const matches = (value) => value?.start === entry.start && value.token === entry.token && value.group === entry.pid;
254
+ for (let attempt = 0; current && !matches(current) && attempt < 3; attempt++) {
255
+ if (running.finished) return;
256
+ await setTimeout(50);
257
+ current = await identity(entry.pid, true, entry.token, observe());
258
+ }
192
259
  if (running.finished) return;
193
260
  if (current?.start !== entry.start || current.token !== entry.token || current.group !== entry.pid) {
194
261
  if (!current) {
@@ -299,12 +366,19 @@ function supervisor(options) {
299
366
  let entry;
300
367
  try {
301
368
  const deadline = Date.now() + 5e3;
302
- let current = await identity(pid, true, token);
369
+ const portable = process.platform !== "linux";
370
+ const gate = async () => {
371
+ if (portable) {
372
+ if (!(await guardianProof(pid, void 0, token, observationMs))?.gated) return void 0;
373
+ }
374
+ return identity(pid, true, token, observe());
375
+ };
376
+ let current = await gate();
303
377
  while (!current?.state.startsWith("T") || current.token !== token) {
304
378
  if (spawnError) throw spawnError;
305
379
  if (exit || Date.now() >= deadline) throw new Error("Child failed to reach the resource setup gate");
306
380
  await setTimeout(10);
307
- current = await identity(pid, true, token);
381
+ current = await gate();
308
382
  }
309
383
  if (current.group !== pid) throw new Error("Child did not create an isolated process group");
310
384
  entry = {
@@ -341,14 +415,14 @@ function supervisor(options) {
341
415
  }
342
416
  return running.handle;
343
417
  } catch (error) {
344
- const current = await identity(pid, true, token);
418
+ const current = await identity(pid, true, token, observe());
345
419
  if (current?.token === token) {
346
420
  const failed = {
347
421
  pid,
348
422
  token,
349
423
  start: current.start
350
424
  };
351
- if (await owns(failed)) try {
425
+ if (await owns(failed, observe())) try {
352
426
  if (process.platform === "win32") await executeCommand(taskkillCommand(pid));
353
427
  else process.kill(-pid, "SIGKILL");
354
428
  } catch {}
@@ -361,7 +435,7 @@ function supervisor(options) {
361
435
  throw error;
362
436
  }
363
437
  }
364
- return {
438
+ const api = {
365
439
  spawn: (input) => serial(() => launch(input, false)),
366
440
  spawnPty: (input) => serial(async () => await launch(input, true)),
367
441
  list: (filter = {}) => serial(async () => {
@@ -389,7 +463,7 @@ function supervisor(options) {
389
463
  };
390
464
  for (const entry of [...entries.values()]) {
391
465
  if (active.has(entry.pid)) continue;
392
- if (!await owns(entry)) {
466
+ if (!await owns(entry, observe())) {
393
467
  entries.delete(entry.pid);
394
468
  result.cleared.push(entry.pid);
395
469
  continue;
@@ -418,7 +492,7 @@ function supervisor(options) {
418
492
  try {
419
493
  const errors = [];
420
494
  for (const entry of [...entries.values()]) try {
421
- if (await owns(entry)) await stopEntry(entry);
495
+ if (await owns(entry, observe())) await stopEntry(entry);
422
496
  else {
423
497
  const running = active.get(entry.pid);
424
498
  if (running) await running.finish(null, null);
@@ -430,12 +504,33 @@ function supervisor(options) {
430
504
  await save();
431
505
  if (errors.length) throw new AggregateError(errors, "Some owned processes could not be stopped");
432
506
  } finally {
507
+ await helper?.close();
433
508
  await registry.close();
434
509
  }
435
510
  });
436
511
  return shutdown;
437
512
  }
438
513
  };
514
+ const stopAll = api.stopAll;
515
+ api.stopAll = () => {
516
+ const stopping = stopAll();
517
+ const forget = () => {
518
+ if (sameProcess.get(registryPath)?.api === api) sameProcess.delete(registryPath);
519
+ };
520
+ stopping.then(forget, forget);
521
+ return stopping;
522
+ };
523
+ sameProcess.set(registryPath, {
524
+ owner: options.owner,
525
+ api
526
+ });
527
+ return api;
528
+ }
529
+ const SUPERVISORS = Symbol.for("@warlock.js/process.supervisors");
530
+ /** Live supervisors of this process by registry path; shared by every copy of this module. */
531
+ function sameProcessSupervisors() {
532
+ const holder = globalThis;
533
+ return holder[SUPERVISORS] ??= /* @__PURE__ */ new Map();
439
534
  }
440
535
 
441
536
  //#endregion