parser.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import {
  2. PLUGIN_HOOK_EVENTS,
  3. type PluginHookCommandHandler,
  4. type PluginHookDiagnostic,
  5. type PluginHookEventName,
  6. type PluginHookSet,
  7. type PluginHookSourceFormat,
  8. } from './contracts.js';
  9. const DEFAULT_TIMEOUT_MS = 5_000;
  10. const MAX_TIMEOUT_MS = 10_000;
  11. const MAX_EXECUTABLE_HANDLERS = 64;
  12. const MAX_MATCHER_LENGTH = 256;
  13. const EVENT_NAMES = new Set<string>(PLUGIN_HOOK_EVENTS);
  14. export function parsePluginHookDocuments(input: {
  15. readonly pluginName: string;
  16. readonly pluginRoot: string;
  17. readonly sourceFormat: PluginHookSourceFormat;
  18. readonly documents: readonly {
  19. readonly sourcePath: string;
  20. readonly value: unknown;
  21. }[];
  22. }): PluginHookSet {
  23. const handlers: PluginHookCommandHandler[] = [];
  24. const diagnostics: PluginHookDiagnostic[] = [];
  25. let declarationOrder = 0;
  26. for (const document of input.documents) {
  27. const hooks = readHooksEnvelope(document.value);
  28. if (!hooks) {
  29. diagnostics.push(
  30. baseDiagnostic(input.pluginName, document.sourcePath, 'HOOK_SCHEMA_INVALID'),
  31. );
  32. continue;
  33. }
  34. for (const [rawEvent, rawGroups] of Object.entries(hooks)) {
  35. if (!EVENT_NAMES.has(rawEvent)) {
  36. diagnostics.push(
  37. baseDiagnostic(input.pluginName, document.sourcePath, 'HOOK_EVENT_UNSUPPORTED'),
  38. );
  39. continue;
  40. }
  41. const event = rawEvent as PluginHookEventName;
  42. const groups = Array.isArray(rawGroups) ? rawGroups : [];
  43. if (!Array.isArray(rawGroups)) {
  44. diagnostics.push({
  45. ...baseDiagnostic(input.pluginName, document.sourcePath, 'HOOK_SCHEMA_INVALID'),
  46. event,
  47. });
  48. continue;
  49. }
  50. for (const group of groups) {
  51. const rawHandlers = isRecord(group) && Array.isArray(group.hooks) ? group.hooks : [];
  52. if (!isRecord(group) || !Array.isArray(group.hooks)) {
  53. diagnostics.push({
  54. ...baseDiagnostic(input.pluginName, document.sourcePath, 'HOOK_SCHEMA_INVALID'),
  55. event,
  56. });
  57. continue;
  58. }
  59. const rawMatcher = group.matcher;
  60. if (
  61. rawMatcher !== undefined &&
  62. (typeof rawMatcher !== 'string' ||
  63. (!rawMatcher.trim() && input.sourceFormat === 'MINIMAX'))
  64. ) {
  65. diagnostics.push({
  66. ...baseDiagnostic(input.pluginName, document.sourcePath, 'HOOK_SCHEMA_INVALID'),
  67. event,
  68. });
  69. continue;
  70. }
  71. const matcher =
  72. typeof rawMatcher === 'string' && rawMatcher.trim() ? rawMatcher : undefined;
  73. if (!isValidMatcher(event, matcher, input.sourceFormat)) {
  74. diagnostics.push({
  75. ...baseDiagnostic(input.pluginName, document.sourcePath, 'HOOK_SCHEMA_INVALID'),
  76. event,
  77. });
  78. continue;
  79. }
  80. for (const rawHandler of rawHandlers) {
  81. const currentOrder = declarationOrder;
  82. declarationOrder += 1;
  83. if (!isRecord(rawHandler)) {
  84. diagnostics.push(
  85. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  86. );
  87. continue;
  88. }
  89. if (rawHandler.async !== undefined && typeof rawHandler.async !== 'boolean') {
  90. diagnostics.push(
  91. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  92. );
  93. continue;
  94. }
  95. if (rawHandler.asyncRewake !== undefined && typeof rawHandler.asyncRewake !== 'boolean') {
  96. diagnostics.push(
  97. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  98. );
  99. continue;
  100. }
  101. if (rawHandler.asyncRewake !== undefined && input.sourceFormat !== 'CLAUDE') {
  102. diagnostics.push(
  103. diagnostic(
  104. input,
  105. document.sourcePath,
  106. event,
  107. currentOrder,
  108. 'HOOK_HANDLER_UNSUPPORTED',
  109. ),
  110. );
  111. continue;
  112. }
  113. if (rawHandler.args !== undefined && !Array.isArray(rawHandler.args)) {
  114. diagnostics.push(
  115. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  116. );
  117. continue;
  118. }
  119. const args = rawHandler.args;
  120. if (Array.isArray(args) && args.some((item) => typeof item !== 'string')) {
  121. diagnostics.push(
  122. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  123. );
  124. continue;
  125. }
  126. if (args !== undefined && input.sourceFormat !== 'CLAUDE') {
  127. diagnostics.push(
  128. diagnostic(
  129. input,
  130. document.sourcePath,
  131. event,
  132. currentOrder,
  133. 'HOOK_HANDLER_UNSUPPORTED',
  134. ),
  135. );
  136. continue;
  137. }
  138. const shell = rawHandler.shell;
  139. if (
  140. shell !== undefined &&
  141. (input.sourceFormat !== 'CLAUDE' || (shell !== 'bash' && shell !== 'powershell'))
  142. ) {
  143. diagnostics.push(
  144. diagnostic(
  145. input,
  146. document.sourcePath,
  147. event,
  148. currentOrder,
  149. input.sourceFormat === 'CLAUDE'
  150. ? 'HOOK_SCHEMA_INVALID'
  151. : 'HOOK_HANDLER_UNSUPPORTED',
  152. ),
  153. );
  154. continue;
  155. }
  156. const condition = rawHandler.if;
  157. if (condition !== undefined && typeof condition !== 'string') {
  158. diagnostics.push(
  159. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  160. );
  161. continue;
  162. }
  163. if (
  164. typeof condition === 'string' &&
  165. (input.sourceFormat !== 'CLAUDE' || !isValidToolCondition(event, condition))
  166. ) {
  167. diagnostics.push(
  168. diagnostic(
  169. input,
  170. document.sourcePath,
  171. event,
  172. currentOrder,
  173. 'HOOK_HANDLER_UNSUPPORTED',
  174. ),
  175. );
  176. continue;
  177. }
  178. if (typeof rawHandler.type !== 'string') {
  179. diagnostics.push(
  180. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  181. );
  182. continue;
  183. }
  184. const type = rawHandler.type;
  185. if (type !== 'command' || rawHandler.async === true || rawHandler.asyncRewake === true) {
  186. diagnostics.push(
  187. diagnostic(
  188. input,
  189. document.sourcePath,
  190. event,
  191. currentOrder,
  192. 'HOOK_HANDLER_UNSUPPORTED',
  193. ),
  194. );
  195. continue;
  196. }
  197. const command = commandValue(rawHandler);
  198. const timeoutMs = timeoutValue(rawHandler.timeout);
  199. if (
  200. rawHandler.additionalContextLimit !== undefined &&
  201. input.sourceFormat === 'CODEX' &&
  202. supportsAdditionalContextLimit(event) &&
  203. !isValidAdditionalContextLimit(rawHandler.additionalContextLimit)
  204. ) {
  205. diagnostics.push(
  206. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  207. );
  208. continue;
  209. }
  210. const additionalContextLimit = readAdditionalContextLimit(
  211. rawHandler.additionalContextLimit,
  212. event,
  213. input.sourceFormat,
  214. );
  215. if (!command || timeoutMs === undefined) {
  216. diagnostics.push(
  217. diagnostic(input, document.sourcePath, event, currentOrder, 'HOOK_SCHEMA_INVALID'),
  218. );
  219. continue;
  220. }
  221. if (handlers.length >= MAX_EXECUTABLE_HANDLERS) {
  222. diagnostics.push(
  223. diagnostic(
  224. input,
  225. document.sourcePath,
  226. event,
  227. currentOrder,
  228. 'HOOK_HANDLER_LIMIT_EXCEEDED',
  229. ),
  230. );
  231. continue;
  232. }
  233. handlers.push({
  234. kind: 'command',
  235. sourceFormat: input.sourceFormat,
  236. pluginName: input.pluginName,
  237. pluginRoot: input.pluginRoot,
  238. sourcePath: document.sourcePath,
  239. event,
  240. ...(matcher?.trim() ? { matcher: matcher.trim() } : {}),
  241. command,
  242. ...(Array.isArray(args) ? { args: args as string[] } : {}),
  243. ...(args === undefined && (shell === 'bash' || shell === 'powershell')
  244. ? { shell }
  245. : {}),
  246. ...(typeof condition === 'string' ? { condition: condition.trim() } : {}),
  247. timeoutMs,
  248. ...(additionalContextLimit !== undefined ? { additionalContextLimit } : {}),
  249. declarationOrder: currentOrder,
  250. });
  251. }
  252. }
  253. }
  254. }
  255. return { handlers, diagnostics };
  256. }
  257. function readAdditionalContextLimit(
  258. value: unknown,
  259. event: PluginHookEventName,
  260. sourceFormat: PluginHookSourceFormat,
  261. ): number | undefined {
  262. if (value === undefined || sourceFormat !== 'CODEX') return undefined;
  263. if (!supportsAdditionalContextLimit(event)) return undefined;
  264. return isValidAdditionalContextLimit(value) ? value : undefined;
  265. }
  266. function supportsAdditionalContextLimit(event: PluginHookEventName): boolean {
  267. return (
  268. event === 'PreToolUse' ||
  269. event === 'PostToolUse' ||
  270. event === 'SessionStart' ||
  271. event === 'UserPromptSubmit' ||
  272. event === 'SubagentStart'
  273. );
  274. }
  275. function isValidAdditionalContextLimit(value: unknown): value is number {
  276. return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
  277. }
  278. function isValidMatcher(
  279. event: PluginHookEventName,
  280. matcher: string | undefined,
  281. sourceFormat: PluginHookSourceFormat,
  282. ): boolean {
  283. if (matcher === undefined) return true;
  284. if (matcher.length > MAX_MATCHER_LENGTH) return false;
  285. if (matcher.trim() === '*' || event === 'UserPromptSubmit' || event === 'Stop') return true;
  286. if (sourceFormat === 'CODEX') {
  287. if (/^[A-Za-z0-9_|]+$/u.test(matcher)) return true;
  288. } else {
  289. const alternatives = matcher.split(/[|,]/u).map((part) => part.trim());
  290. if (alternatives.every((part) => /^[A-Za-z0-9_.:/-]+$/u.test(part))) return true;
  291. }
  292. return isSafePluginHookMatcher(matcher);
  293. }
  294. function isValidToolCondition(event: PluginHookEventName, condition: string): boolean {
  295. if (event !== 'PreToolUse' && event !== 'PermissionRequest' && event !== 'PostToolUse')
  296. return false;
  297. const trimmed = condition.trim();
  298. if (!trimmed || trimmed.length > MAX_MATCHER_LENGTH) return false;
  299. const match = /^([A-Za-z0-9_.:/-]+)\(([^\r\n()]*)\)$/u.exec(trimmed);
  300. return Boolean(match?.[1] && match[2] !== undefined);
  301. }
  302. export function isSafePluginHookMatcher(pattern: string): boolean {
  303. if (!pattern || pattern.length > MAX_MATCHER_LENGTH || hasUnsupportedGroupExtension(pattern)) {
  304. return false;
  305. }
  306. let escaped = false;
  307. for (let index = 0; index < pattern.length; index += 1) {
  308. const char = pattern[index];
  309. if (escaped) {
  310. const width = safeEscapeWidth(pattern, index);
  311. if (width === 0) return false;
  312. index += width - 1;
  313. escaped = false;
  314. continue;
  315. }
  316. if (char === '\\') {
  317. escaped = true;
  318. continue;
  319. }
  320. if (char === ')' && /[*+?{]/u.test(pattern[index + 1] ?? '')) return false;
  321. }
  322. if (escaped) return false;
  323. if (hasExcessiveRepeatedQuantifiedAtom(pattern)) return false;
  324. try {
  325. RegExp(pattern, 'u');
  326. return true;
  327. } catch {
  328. return false;
  329. }
  330. }
  331. /**
  332. * Compatible's JavaScript regexp engine and Codex's Rust regexp engine both support
  333. * non-capturing groups. Their look-around and named-group support differs, so
  334. * keep the portable subset (`(?:...)`) and reject every other `(?...)` form.
  335. */
  336. function hasUnsupportedGroupExtension(pattern: string): boolean {
  337. for (
  338. let offset = pattern.indexOf('(?');
  339. offset >= 0;
  340. offset = pattern.indexOf('(?', offset + 2)
  341. ) {
  342. if (pattern[offset + 2] !== ':') return true;
  343. }
  344. return false;
  345. }
  346. function hasExcessiveRepeatedQuantifiedAtom(pattern: string): boolean {
  347. const counts = new Map<string, number>();
  348. for (const match of pattern.matchAll(/((?:\\.|[A-Za-z0-9_.-]))(?:[*+?]|\{\d+(?:,\d*)?\})/gu)) {
  349. const atom = match[1];
  350. if (!atom) continue;
  351. const count = (counts.get(atom) ?? 0) + 1;
  352. if (count >= 4) return true;
  353. counts.set(atom, count);
  354. }
  355. return false;
  356. }
  357. function safeEscapeWidth(pattern: string, index: number): number {
  358. const char = pattern[index];
  359. if (!char || /[1-9kKpPAZGz]/u.test(char)) return 0;
  360. if (char === 'x') return /^[0-9A-Fa-f]{2}$/u.test(pattern.slice(index + 1, index + 3)) ? 3 : 0;
  361. if (char === 'u') return /^[0-9A-Fa-f]{4}$/u.test(pattern.slice(index + 1, index + 5)) ? 5 : 0;
  362. return /[dDsSwWbBfnrtv0\\.^$*+?()[\]{}|/-]/u.test(char) ? 1 : 0;
  363. }
  364. function readHooksEnvelope(value: unknown): Record<string, unknown> | undefined {
  365. if (!isRecord(value)) return undefined;
  366. return isRecord(value.hooks) ? value.hooks : value;
  367. }
  368. function commandValue(value: Record<string, unknown>): string | undefined {
  369. const command =
  370. process.platform === 'win32'
  371. ? (value.commandWindows ?? value.command_windows ?? value.command)
  372. : value.command;
  373. return typeof command === 'string' && command.trim() ? command.trim() : undefined;
  374. }
  375. function timeoutValue(value: unknown): number | undefined {
  376. if (value === undefined) return DEFAULT_TIMEOUT_MS;
  377. if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 10) {
  378. return undefined;
  379. }
  380. return Math.min(value * 1_000, MAX_TIMEOUT_MS);
  381. }
  382. function baseDiagnostic(
  383. pluginName: string,
  384. sourcePath: string,
  385. code: string,
  386. ): PluginHookDiagnostic {
  387. return { pluginName, sourcePath, code };
  388. }
  389. function diagnostic(
  390. input: { readonly pluginName: string },
  391. sourcePath: string,
  392. event: PluginHookEventName,
  393. declarationOrder: number,
  394. code: string,
  395. ): PluginHookDiagnostic {
  396. return { pluginName: input.pluginName, sourcePath, event, declarationOrder, code };
  397. }
  398. function isRecord(value: unknown): value is Record<string, unknown> {
  399. return typeof value === 'object' && value !== null && !Array.isArray(value);
  400. }