forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparser.ts
More file actions
1804 lines (1695 loc) · 65.1 KB
/
parser.ts
File metadata and controls
1804 lines (1695 loc) · 65.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execa } from 'execa'
import { logForDebugging } from '../debug.js'
import { memoizeWithLRU } from '../memoize.js'
import { getCachedPowerShellPath } from '../shell/powershellDetection.js'
import { jsonParse } from '../slowOperations.js'
// ---------------------------------------------------------------------------
// Public types describing the parsed output returned to callers.
// These map to System.Management.Automation.Language AST classes.
// Raw internal types (RawParsedOutput etc.) are defined further below.
// ---------------------------------------------------------------------------
/**
* The PowerShell AST element type for pipeline elements.
* Maps directly to CommandBaseAst derivatives in System.Management.Automation.Language.
*/
type PipelineElementType =
| 'CommandAst'
| 'CommandExpressionAst'
| 'ParenExpressionAst'
/**
* The AST node type for individual command elements (arguments, expressions).
* Used to classify each element during the AST walk so TypeScript can derive
* security flags without extra Find-AstNodes calls in PowerShell.
*/
type CommandElementType =
| 'ScriptBlock'
| 'SubExpression'
| 'ExpandableString'
| 'MemberInvocation'
| 'Variable'
| 'StringConstant'
| 'Parameter'
| 'Other'
/**
* A child node of a command element (one level deep). Populated for
* CommandParameterAst → .Argument (colon-bound parameters like
* `-InputObject:$env:SECRET`). Consumers check `child.type` to classify
* the bound value (Variable, StringConstant, Other) without parsing text.
*/
export type CommandElementChild = {
type: CommandElementType
text: string
}
/**
* The PowerShell AST statement type.
* Maps directly to StatementAst derivatives in System.Management.Automation.Language.
*/
type StatementType =
| 'PipelineAst'
| 'PipelineChainAst'
| 'AssignmentStatementAst'
| 'IfStatementAst'
| 'ForStatementAst'
| 'ForEachStatementAst'
| 'WhileStatementAst'
| 'DoWhileStatementAst'
| 'DoUntilStatementAst'
| 'SwitchStatementAst'
| 'TryStatementAst'
| 'TrapStatementAst'
| 'FunctionDefinitionAst'
| 'DataStatementAst'
| 'UnknownStatementAst'
/**
* A command invocation within a pipeline segment.
*/
export type ParsedCommandElement = {
/** The command/cmdlet name (e.g., "Get-ChildItem", "git") */
name: string
/** The command name type: cmdlet, application (exe), or unknown */
nameType: 'cmdlet' | 'application' | 'unknown'
/** The AST element type from PowerShell's parser */
elementType: PipelineElementType
/** All arguments as strings (includes flags like "-Recurse") */
args: string[]
/** The full text of this command element */
text: string
/** AST node types for each element in this command (arguments, expressions, etc.) */
elementTypes?: CommandElementType[]
/**
* Child nodes of each argument, aligned with `args[]` (so
* `children[i]` ↔ `args[i]` ↔ `elementTypes[i+1]`). Only populated for
* Parameter elements with a colon-bound argument. Undefined for elements
* with no children. Lets consumers check `children[i].some(c => c.type
* !== 'StringConstant')` instead of parsing the arg text for `:` + `$`.
*/
children?: (CommandElementChild[] | undefined)[]
/** Redirections on this command element (from nested commands in && / || chains) */
redirections?: ParsedRedirection[]
}
/**
* A redirection found in the command.
*/
type ParsedRedirection = {
/** The redirection operator */
operator: '>' | '>>' | '2>' | '2>>' | '*>' | '*>>' | '2>&1'
/** The target (file path or stream number) */
target: string
/** Whether this is a merging redirection like 2>&1 */
isMerging: boolean
}
/**
* A parsed statement from PowerShell.
* Can be a pipeline, assignment, control flow statement, etc.
*/
type ParsedStatement = {
/** The AST statement type from PowerShell's parser */
statementType: StatementType
/** Individual commands in this statement (for pipelines) */
commands: ParsedCommandElement[]
/** Redirections on this statement */
redirections: ParsedRedirection[]
/** Full text of the statement */
text: string
/**
* For control flow statements (if, for, foreach, while, try, etc.),
* commands found recursively inside the body blocks.
* Uses FindAll() to extract ALL nested CommandAst nodes at any depth.
*/
nestedCommands?: ParsedCommandElement[]
/**
* Security-relevant AST patterns found via FindAll() on the entire statement,
* regardless of statement type. This catches patterns that elementTypes may
* miss (e.g. member invocations inside assignments, subexpressions in
* non-pipeline statements). Computed in the PS1 script using instanceof
* checks against the PowerShell AST type system.
*/
securityPatterns?: {
hasMemberInvocations?: boolean
hasSubExpressions?: boolean
hasExpandableStrings?: boolean
hasScriptBlocks?: boolean
}
}
/**
* A variable reference found in the command.
*/
type ParsedVariable = {
/** The variable path (e.g., "HOME", "env:PATH", "global:x") */
path: string
/** Whether this variable uses splatting (@var instead of $var) */
isSplatted: boolean
}
/**
* A parse error from PowerShell's parser.
*/
type ParseError = {
message: string
errorId: string
}
/**
* The complete parsed result from the PowerShell AST parser.
*/
export type ParsedPowerShellCommand = {
/** Whether the command parsed successfully (no syntax errors) */
valid: boolean
/** Parse errors, if any */
errors: ParseError[]
/** Top-level statements, separated by ; or newlines */
statements: ParsedStatement[]
/** All variable references found */
variables: ParsedVariable[]
/** Whether the token stream contains a stop-parsing (--%) token */
hasStopParsing: boolean
/** The original command text */
originalCommand: string
/**
* All .NET type literals found anywhere in the AST (TypeExpressionAst +
* TypeConstraintAst). TypeName.FullName — the literal text as written, NOT
* the resolved .NET type (e.g. [int] → "int", not "System.Int32").
* Consumed by the CLM-allowlist check in powershellSecurity.ts.
*/
typeLiterals?: string[]
/**
* Whether the command contains `using module` or `using assembly` statements.
* These load external code (modules/assemblies) and execute their top-level
* script body or module initializers. The using statement is a sibling of
* the named blocks on ScriptBlockAst, not a child, so it is not visible
* to Process-BlockStatements or any downstream command walker.
*/
hasUsingStatements?: boolean
/**
* Whether the command contains `#Requires` directives (ScriptRequirements).
* `#Requires -Modules <name>` triggers module loading from PSModulePath.
*/
hasScriptRequirements?: boolean
}
// ---------------------------------------------------------------------------
// Default 5s is fine for interactive use (warm pwsh spawn is ~450ms). Windows
// CI under Defender/AMSI load can exceed 5s on consecutive spawns even after
// CAN_SPAWN_PARSE_SCRIPT() warms the JIT (run 23574701241 windows-shard-5:
// attackVectors F1 hit 2×5s timeout → valid:false → 'ask' instead of 'deny').
// Override via env for tests. Read inside parsePowerShellCommandImpl, not
// top-level, per CLAUDE.md (globalSettings.env ordering).
const DEFAULT_PARSE_TIMEOUT_MS = 5_000
function getParseTimeoutMs(): number {
const env = process.env.CLAUDE_CODE_PWSH_PARSE_TIMEOUT_MS
if (env) {
const parsed = parseInt(env, 10)
if (!isNaN(parsed) && parsed > 0) return parsed
}
return DEFAULT_PARSE_TIMEOUT_MS
}
// MAX_COMMAND_LENGTH is derived from PARSE_SCRIPT_BODY.length below (after the
// script body is defined) so it cannot go stale as the script grows.
/**
* The PowerShell parse script inlined as a string constant.
* This avoids needing to read from disk at runtime (the file may not exist
* in bundled builds). The script uses the native PowerShell AST parser to
* analyze a command and output structured JSON.
*/
// Raw types describing PS script JSON output (exported for testing)
export type RawCommandElement = {
type: string // .GetType().Name e.g. "StringConstantExpressionAst"
text: string // .Extent.Text
value?: string // .Value if available (resolves backtick escapes)
expressionType?: string // .Expression.GetType().Name for CommandExpressionAst
children?: { type: string; text: string }[] // CommandParameterAst.Argument, one level
}
export type RawRedirection = {
type: string // "FileRedirectionAst" or "MergingRedirectionAst"
append?: boolean // .Append (FileRedirectionAst only)
fromStream?: string // .FromStream.ToString() e.g. "Output", "Error", "All"
locationText?: string // .Location.Extent.Text (FileRedirectionAst only)
}
export type RawPipelineElement = {
type: string // .GetType().Name e.g. "CommandAst", "CommandExpressionAst"
text: string // .Extent.Text
commandElements?: RawCommandElement[]
redirections?: RawRedirection[]
expressionType?: string // for CommandExpressionAst: .Expression.GetType().Name
}
export type RawStatement = {
type: string // .GetType().Name e.g. "PipelineAst", "IfStatementAst", "TrapStatementAst"
text: string // .Extent.Text
elements?: RawPipelineElement[] // for PipelineAst: the pipeline elements
nestedCommands?: RawPipelineElement[] // commands found via FindAll (all statement types)
redirections?: RawRedirection[] // FileRedirectionAst found via FindAll (non-PipelineAst only)
securityPatterns?: {
// Security-relevant AST node types found via FindAll on the statement
hasMemberInvocations?: boolean
hasSubExpressions?: boolean
hasExpandableStrings?: boolean
hasScriptBlocks?: boolean
}
}
type RawParsedOutput = {
valid: boolean
errors: { message: string; errorId: string }[]
statements: RawStatement[]
variables: { path: string; isSplatted: boolean }[]
hasStopParsing: boolean
originalCommand: string
typeLiterals?: string[]
hasUsingStatements?: boolean
hasScriptRequirements?: boolean
}
// This is the canonical copy of the parse script. There is no separate .ps1 file.
/**
* The core parse logic.
* The command is passed via Base64-encoded $EncodedCommand variable
* to avoid here-string injection attacks.
*
* SECURITY — top-level ParamBlock: ScriptBlockAst.ParamBlock is a SIBLING of
* the named blocks (Begin/Process/End/Clean/DynamicParam), not nested inside
* them, so Process-BlockStatements never reaches it. Commands inside param()
* default-value expressions and attribute arguments (e.g. [ValidateScript({...})])
* were invisible to every downstream check. PoC:
* param($x = (Remove-Item /)); Get-Process → only Get-Process surfaced
* param([ValidateScript({rm /;$true})]$x='t') → rm invisible, runs on bind
* Function-level param() IS covered: FindAll on the FunctionDefinitionAst
* statement recurses into its descendants. The gap was only the script-level
* ParamBlock. ParamBlockAst has .Parameters (not .Statements) so we FindAll
* on it directly rather than reusing Process-BlockStatements. We only emit a
* statement if there is something to report, to avoid noise for plain
* param($x) declarations. (Kept compact in-script to preserve argv budget.)
*/
/**
* PS1 parse script. Comments live here (not inline) — every char inside the
* backticks eats into WINDOWS_MAX_COMMAND_LENGTH (argv budget).
*
* Structure:
* - Get-RawCommandElements: extract CommandAst element data (type, text, value,
* expressionType, children for colon-bound param .Argument)
* - Get-RawRedirections: extract FileRedirectionAst operator+target
* - Get-SecurityPatterns: FindAll for security flags (hasSubExpressions via
* Sub/Array/ParenExpressionAst, hasScriptBlocks, etc.)
* - Type literals: emit TypeExpressionAst names for CLM allowlist check
* - --% token: PS7 MinusMinus, PS5.1 Generic kind
* - CommandExpressionAst.Redirections: inherits from CommandBaseAst —
* `1 > /tmp/x` statement has FileRedirectionAst that element-iteration misses
* - Nested commands: FindAll for ALL statement types (if/for/foreach/while/
* switch/try/function/assignment/PipelineChainAst) — skip direct pipeline
* elements already in the loop
*/
// exported for testing
export const PARSE_SCRIPT_BODY = `
if (-not $EncodedCommand) {
Write-Output '{"valid":false,"errors":[{"message":"No command provided","errorId":"NoInput"}],"statements":[],"variables":[],"hasStopParsing":false,"originalCommand":""}'
exit 0
}
$Command = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($EncodedCommand))
$tokens = $null
$parseErrors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
$Command,
[ref]$tokens,
[ref]$parseErrors
)
$allVariables = [System.Collections.ArrayList]::new()
function Get-RawCommandElements {
param([System.Management.Automation.Language.CommandAst]$CmdAst)
$elems = [System.Collections.ArrayList]::new()
foreach ($ce in $CmdAst.CommandElements) {
$ceData = @{ type = $ce.GetType().Name; text = $ce.Extent.Text }
if ($ce.PSObject.Properties['Value'] -and $null -ne $ce.Value -and $ce.Value -is [string]) {
$ceData.value = $ce.Value
}
if ($ce -is [System.Management.Automation.Language.CommandExpressionAst]) {
$ceData.expressionType = $ce.Expression.GetType().Name
}
$a=$ce.Argument;if($a){$ceData.children=@(@{type=$a.GetType().Name;text=$a.Extent.Text})}
[void]$elems.Add($ceData)
}
return $elems
}
function Get-RawRedirections {
param($Redirections)
$result = [System.Collections.ArrayList]::new()
foreach ($redir in $Redirections) {
$redirData = @{ type = $redir.GetType().Name }
if ($redir -is [System.Management.Automation.Language.FileRedirectionAst]) {
$redirData.append = [bool]$redir.Append
$redirData.fromStream = $redir.FromStream.ToString()
$redirData.locationText = $redir.Location.Extent.Text
}
[void]$result.Add($redirData)
}
return $result
}
function Get-SecurityPatterns($A) {
$p = @{}
foreach ($n in $A.FindAll({ param($x)
$x -is [System.Management.Automation.Language.MemberExpressionAst] -or
$x -is [System.Management.Automation.Language.SubExpressionAst] -or
$x -is [System.Management.Automation.Language.ArrayExpressionAst] -or
$x -is [System.Management.Automation.Language.ExpandableStringExpressionAst] -or
$x -is [System.Management.Automation.Language.ScriptBlockExpressionAst] -or
$x -is [System.Management.Automation.Language.ParenExpressionAst]
}, $true)) { switch ($n.GetType().Name) {
'InvokeMemberExpressionAst' { $p.hasMemberInvocations = $true }
'MemberExpressionAst' { $p.hasMemberInvocations = $true }
'SubExpressionAst' { $p.hasSubExpressions = $true }
'ArrayExpressionAst' { $p.hasSubExpressions = $true }
'ParenExpressionAst' { $p.hasSubExpressions = $true }
'ExpandableStringExpressionAst' { $p.hasExpandableStrings = $true }
'ScriptBlockExpressionAst' { $p.hasScriptBlocks = $true }
}}
if ($p.Count -gt 0) { return $p }
return $null
}
$varExprs = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.VariableExpressionAst] }, $true)
foreach ($v in $varExprs) {
[void]$allVariables.Add(@{
path = $v.VariablePath.ToString()
isSplatted = [bool]$v.Splatted
})
}
$typeLiterals = [System.Collections.ArrayList]::new()
foreach ($t in $ast.FindAll({ param($n)
$n -is [System.Management.Automation.Language.TypeExpressionAst] -or
$n -is [System.Management.Automation.Language.TypeConstraintAst]
}, $true)) { [void]$typeLiterals.Add($t.TypeName.FullName) }
$hasStopParsing = $false
$tk = [System.Management.Automation.Language.TokenKind]
foreach ($tok in $tokens) {
if ($tok.Kind -eq $tk::MinusMinus) { $hasStopParsing = $true; break }
if ($tok.Kind -eq $tk::Generic -and ($tok.Text -replace '[\u2013\u2014\u2015]','-') -eq '--%') {
$hasStopParsing = $true; break
}
}
$statements = [System.Collections.ArrayList]::new()
function Process-BlockStatements {
param($Block)
if (-not $Block) { return }
foreach ($stmt in $Block.Statements) {
$statement = @{
type = $stmt.GetType().Name
text = $stmt.Extent.Text
}
if ($stmt -is [System.Management.Automation.Language.PipelineAst]) {
$elements = [System.Collections.ArrayList]::new()
foreach ($element in $stmt.PipelineElements) {
$elemData = @{
type = $element.GetType().Name
text = $element.Extent.Text
}
if ($element -is [System.Management.Automation.Language.CommandAst]) {
$elemData.commandElements = @(Get-RawCommandElements -CmdAst $element)
$elemData.redirections = @(Get-RawRedirections -Redirections $element.Redirections)
} elseif ($element -is [System.Management.Automation.Language.CommandExpressionAst]) {
$elemData.expressionType = $element.Expression.GetType().Name
$elemData.redirections = @(Get-RawRedirections -Redirections $element.Redirections)
}
[void]$elements.Add($elemData)
}
$statement.elements = @($elements)
$allNestedCmds = $stmt.FindAll(
{ param($node) $node -is [System.Management.Automation.Language.CommandAst] },
$true
)
$nestedCmds = [System.Collections.ArrayList]::new()
foreach ($cmd in $allNestedCmds) {
if ($cmd.Parent -eq $stmt) { continue }
$nested = @{
type = $cmd.GetType().Name
text = $cmd.Extent.Text
commandElements = @(Get-RawCommandElements -CmdAst $cmd)
redirections = @(Get-RawRedirections -Redirections $cmd.Redirections)
}
[void]$nestedCmds.Add($nested)
}
if ($nestedCmds.Count -gt 0) {
$statement.nestedCommands = @($nestedCmds)
}
$r = $stmt.FindAll({param($n) $n -is [System.Management.Automation.Language.FileRedirectionAst]}, $true)
if ($r.Count -gt 0) {
$rr = @(Get-RawRedirections -Redirections $r)
$statement.redirections = if ($statement.redirections) { @($statement.redirections) + $rr } else { $rr }
}
} else {
$nestedCmdAsts = $stmt.FindAll(
{ param($node) $node -is [System.Management.Automation.Language.CommandAst] },
$true
)
$nested = [System.Collections.ArrayList]::new()
foreach ($cmd in $nestedCmdAsts) {
[void]$nested.Add(@{
type = 'CommandAst'
text = $cmd.Extent.Text
commandElements = @(Get-RawCommandElements -CmdAst $cmd)
redirections = @(Get-RawRedirections -Redirections $cmd.Redirections)
})
}
if ($nested.Count -gt 0) {
$statement.nestedCommands = @($nested)
}
$r = $stmt.FindAll({param($n) $n -is [System.Management.Automation.Language.FileRedirectionAst]}, $true)
if ($r.Count -gt 0) { $statement.redirections = @(Get-RawRedirections -Redirections $r) }
}
$sp = Get-SecurityPatterns $stmt
if ($sp) { $statement.securityPatterns = $sp }
[void]$statements.Add($statement)
}
if ($Block.Traps) {
foreach ($trap in $Block.Traps) {
$statement = @{
type = 'TrapStatementAst'
text = $trap.Extent.Text
}
$nestedCmdAsts = $trap.FindAll(
{ param($node) $node -is [System.Management.Automation.Language.CommandAst] },
$true
)
$nestedCmds = [System.Collections.ArrayList]::new()
foreach ($cmd in $nestedCmdAsts) {
$nested = @{
type = $cmd.GetType().Name
text = $cmd.Extent.Text
commandElements = @(Get-RawCommandElements -CmdAst $cmd)
redirections = @(Get-RawRedirections -Redirections $cmd.Redirections)
}
[void]$nestedCmds.Add($nested)
}
if ($nestedCmds.Count -gt 0) {
$statement.nestedCommands = @($nestedCmds)
}
$r = $trap.FindAll({param($n) $n -is [System.Management.Automation.Language.FileRedirectionAst]}, $true)
if ($r.Count -gt 0) { $statement.redirections = @(Get-RawRedirections -Redirections $r) }
$sp = Get-SecurityPatterns $trap
if ($sp) { $statement.securityPatterns = $sp }
[void]$statements.Add($statement)
}
}
}
Process-BlockStatements -Block $ast.BeginBlock
Process-BlockStatements -Block $ast.ProcessBlock
Process-BlockStatements -Block $ast.EndBlock
Process-BlockStatements -Block $ast.CleanBlock
Process-BlockStatements -Block $ast.DynamicParamBlock
if ($ast.ParamBlock) {
$pb = $ast.ParamBlock
$pn = [System.Collections.ArrayList]::new()
foreach ($c in $pb.FindAll({param($n) $n -is [System.Management.Automation.Language.CommandAst]}, $true)) {
[void]$pn.Add(@{type='CommandAst';text=$c.Extent.Text;commandElements=@(Get-RawCommandElements -CmdAst $c);redirections=@(Get-RawRedirections -Redirections $c.Redirections)})
}
$pr = $pb.FindAll({param($n) $n -is [System.Management.Automation.Language.FileRedirectionAst]}, $true)
$ps = Get-SecurityPatterns $pb
if ($pn.Count -gt 0 -or $pr.Count -gt 0 -or $ps) {
$st = @{type='ParamBlockAst';text=$pb.Extent.Text}
if ($pn.Count -gt 0) { $st.nestedCommands = @($pn) }
if ($pr.Count -gt 0) { $st.redirections = @(Get-RawRedirections -Redirections $pr) }
if ($ps) { $st.securityPatterns = $ps }
[void]$statements.Add($st)
}
}
$hasUsingStatements = $ast.UsingStatements -and $ast.UsingStatements.Count -gt 0
$hasScriptRequirements = $ast.ScriptRequirements -ne $null
$output = @{
valid = ($parseErrors.Count -eq 0)
errors = @($parseErrors | ForEach-Object {
@{
message = $_.Message
errorId = $_.ErrorId
}
})
statements = @($statements)
variables = @($allVariables)
hasStopParsing = $hasStopParsing
originalCommand = $Command
typeLiterals = @($typeLiterals)
hasUsingStatements = [bool]$hasUsingStatements
hasScriptRequirements = [bool]$hasScriptRequirements
}
$output | ConvertTo-Json -Depth 10 -Compress
`
// ---------------------------------------------------------------------------
// Windows CreateProcess has a 32,767 char command-line limit. The encoding
// chain is:
// command (N UTF-8 bytes) → Base64 (~4N/3 chars) → $EncodedCommand = '...'\n
// → full script (wrapper + PARSE_SCRIPT_BODY) → UTF-16LE (2× bytes)
// → Base64 (4/3× chars) → -EncodedCommand argv
// Final cmdline ≈ argv_overhead + (wrapper + 4N/3 + body) × 8/3
//
// Solving for N (UTF-8 bytes) with a 32,767 cap:
// script_budget = (32767 - argv_overhead) × 3/8
// cmd_b64_budget = script_budget - PARSE_SCRIPT_BODY.length - wrapper
// N = cmd_b64_budget × 3/4 - safety_margin
//
// SECURITY: N is a UTF-8 BYTE budget, not a UTF-16 code-unit budget. The
// length gate MUST measure Buffer.byteLength(command, 'utf8'), not
// command.length. A BMP character in U+0800–U+FFFF (CJK ideographs, most
// non-Latin scripts) is 1 UTF-16 code unit but 3 UTF-8 bytes. With
// PARSE_SCRIPT_BODY ≈ 10.6K, N ≈ 1,092 bytes. Comparing against .length
// permits a 1,092-code-unit pure-CJK command (≈3,276 UTF-8 bytes) → inner
// base64 ≈ 4,368 chars → final argv ≈ 40K chars, overflowing 32,767 by
// ~7.4K. CreateProcess fails → valid:false → parse-fail degradation (deny
// rules silently downgrade to ask). Finding #36.
//
// COMPUTED from PARSE_SCRIPT_BODY.length so it cannot drift. The prior
// hardcoded value (4,500) was derived from a ~6K body estimate; the body is
// actually ~11K chars, so the real ceiling was ~1,850. Commands in the
// 1,850–4,500 range passed this gate but then failed CreateProcess on
// Windows, returning valid=false and skipping all AST-based security checks.
//
// Unix argv limits are typically 2MB+ (ARG_MAX) with ~128KB per-argument
// limit (MAX_ARG_STRLEN on Linux; macOS has no per-arg limit below ARG_MAX).
// At MAX=4,500 the -EncodedCommand argument is ~45KB — well under either.
// Applying the Windows-derived limit on Unix would REGRESS: commands in the
// ~1K–4.5K range previously parsed successfully and reached the sub-command
// deny loop at powershellPermissions.ts; rejecting them pre-spawn degrades
// user-configured deny rules from deny→ask for compound commands with a
// denied cmdlet buried mid-script. So the Windows limit is platform-gated.
//
// If the Windows limit becomes too restrictive, switch to -File with a temp
// file for large inputs.
// ---------------------------------------------------------------------------
const WINDOWS_ARGV_CAP = 32_767
// pwsh path + " -NoProfile -NonInteractive -NoLogo -EncodedCommand " +
// argv quoting. A long Windows pwsh path (C:\Program Files\PowerShell\7\
// pwsh.exe) + flags is ~95 chars; 200 leaves headroom for unusual installs.
const FIXED_ARGV_OVERHEAD = 200
// "$EncodedCommand = '" + "'\n" wrapper around the user command's base64
const ENCODED_CMD_WRAPPER = `$EncodedCommand = ''\n`.length
// Margin for base64 padding rounding (≤4 chars at each of 2 levels) and minor
// estimation drift. Multibyte expansion is NOT absorbed here — the gate
// measures actual UTF-8 bytes (Buffer.byteLength), not code units.
const SAFETY_MARGIN = 100
const SCRIPT_CHARS_BUDGET = ((WINDOWS_ARGV_CAP - FIXED_ARGV_OVERHEAD) * 3) / 8
const CMD_B64_BUDGET =
SCRIPT_CHARS_BUDGET - PARSE_SCRIPT_BODY.length - ENCODED_CMD_WRAPPER
// Exported for drift-guard tests (the drift-prone value is the Windows one).
// Unit: UTF-8 BYTES. Compare against Buffer.byteLength, not .length.
export const WINDOWS_MAX_COMMAND_LENGTH = Math.max(
0,
Math.floor((CMD_B64_BUDGET * 3) / 4) - SAFETY_MARGIN,
)
// Pre-existing value, known to work on Unix. See comment above re: why the
// Windows derivation must NOT be applied here. Unit: UTF-8 BYTES — for ASCII
// commands (the common case) bytes==chars so no regression; for multibyte
// commands this is slightly tighter but still far below Unix ARG_MAX (~128KB
// per-arg), so the argv spawn cannot overflow.
const UNIX_MAX_COMMAND_LENGTH = 4_500
// Unit: UTF-8 BYTES (see SECURITY note above).
export const MAX_COMMAND_LENGTH =
process.platform === 'win32'
? WINDOWS_MAX_COMMAND_LENGTH
: UNIX_MAX_COMMAND_LENGTH
const INVALID_RESULT_BASE: Omit<
ParsedPowerShellCommand,
'errors' | 'originalCommand'
> = {
valid: false,
statements: [],
variables: [],
hasStopParsing: false,
}
function makeInvalidResult(
command: string,
message: string,
errorId: string,
): ParsedPowerShellCommand {
return {
...INVALID_RESULT_BASE,
errors: [{ message, errorId }],
originalCommand: command,
}
}
/**
* Base64-encode a string as UTF-16LE, which is the encoding required by
* PowerShell's -EncodedCommand parameter.
*/
function toUtf16LeBase64(text: string): string {
if (typeof Buffer !== 'undefined') {
return Buffer.from(text, 'utf16le').toString('base64')
}
// Fallback for non-Node environments
const bytes: number[] = []
for (let i = 0; i < text.length; i++) {
const code = text.charCodeAt(i)
bytes.push(code & 0xff, (code >> 8) & 0xff)
}
return btoa(bytes.map(b => String.fromCharCode(b)).join(''))
}
/**
* Build the full PowerShell script that parses a command.
* The user command is Base64-encoded (UTF-8) and embedded in a variable
* to prevent injection attacks.
*/
function buildParseScript(command: string): string {
const encoded =
typeof Buffer !== 'undefined'
? Buffer.from(command, 'utf8').toString('base64')
: btoa(
new TextEncoder()
.encode(command)
.reduce((s, b) => s + String.fromCharCode(b), ''),
)
return `$EncodedCommand = '${encoded}'\n${PARSE_SCRIPT_BODY}`
}
/**
* Ensure a value is an array. PowerShell 5.1's ConvertTo-Json may unwrap
* single-element arrays into plain objects.
*/
function ensureArray<T>(value: T | T[] | undefined | null): T[] {
if (value === undefined || value === null) {
return []
}
return Array.isArray(value) ? value : [value]
}
/** Map raw .NET AST type name to our StatementType union */
// exported for testing
export function mapStatementType(rawType: string): StatementType {
switch (rawType) {
case 'PipelineAst':
return 'PipelineAst'
case 'PipelineChainAst':
return 'PipelineChainAst'
case 'AssignmentStatementAst':
return 'AssignmentStatementAst'
case 'IfStatementAst':
return 'IfStatementAst'
case 'ForStatementAst':
return 'ForStatementAst'
case 'ForEachStatementAst':
return 'ForEachStatementAst'
case 'WhileStatementAst':
return 'WhileStatementAst'
case 'DoWhileStatementAst':
return 'DoWhileStatementAst'
case 'DoUntilStatementAst':
return 'DoUntilStatementAst'
case 'SwitchStatementAst':
return 'SwitchStatementAst'
case 'TryStatementAst':
return 'TryStatementAst'
case 'TrapStatementAst':
return 'TrapStatementAst'
case 'FunctionDefinitionAst':
return 'FunctionDefinitionAst'
case 'DataStatementAst':
return 'DataStatementAst'
default:
return 'UnknownStatementAst'
}
}
/** Map raw .NET AST type name to our CommandElementType union */
// exported for testing
export function mapElementType(
rawType: string,
expressionType?: string,
): CommandElementType {
switch (rawType) {
case 'ScriptBlockExpressionAst':
return 'ScriptBlock'
case 'SubExpressionAst':
case 'ArrayExpressionAst':
// SECURITY: ArrayExpressionAst (@()) is a sibling of SubExpressionAst,
// not a subclass. Both evaluate arbitrary pipelines with side effects:
// Get-ChildItem @(Remove-Item ./data) runs Remove-Item inside @().
// Map both to SubExpression so hasSubExpressions fires and isReadOnlyCommand
// rejects (it doesn't check nestedCommands, only pipeline.commands[]).
return 'SubExpression'
case 'ExpandableStringExpressionAst':
return 'ExpandableString'
case 'InvokeMemberExpressionAst':
case 'MemberExpressionAst':
return 'MemberInvocation'
case 'VariableExpressionAst':
return 'Variable'
case 'StringConstantExpressionAst':
case 'ConstantExpressionAst':
// ConstantExpressionAst covers numeric literals (5, 3.14). For
// permission purposes a numeric literal is as safe as a string
// literal — it's an inert value, not code. Without this mapping,
// `-Seconds:5` produced children[0].type='Other' and consumers
// checking `children.some(c => c.type !== 'StringConstant')` would
// false-positive ask on harmless numeric args.
return 'StringConstant'
case 'CommandParameterAst':
return 'Parameter'
case 'ParenExpressionAst':
return 'SubExpression'
case 'CommandExpressionAst':
// Delegate to the wrapped expression type so we catch SubExpressionAst,
// ExpandableStringExpressionAst, ScriptBlockExpressionAst, etc.
// without maintaining a manual list. Falls through to 'Other' if the
// inner type is unrecognised.
if (expressionType) {
return mapElementType(expressionType)
}
return 'Other'
default:
return 'Other'
}
}
/** Classify command name as cmdlet, application, or unknown */
// exported for testing
export function classifyCommandName(
name: string,
): 'cmdlet' | 'application' | 'unknown' {
if (/^[A-Za-z]+-[A-Za-z][A-Za-z0-9_]*$/.test(name)) {
return 'cmdlet'
}
if (/[.\\/]/.test(name)) {
return 'application'
}
return 'unknown'
}
/** Strip module prefix from command name (e.g. "Microsoft.PowerShell.Utility\\Invoke-Expression" -> "Invoke-Expression") */
// exported for testing
export function stripModulePrefix(name: string): string {
const idx = name.lastIndexOf('\\')
if (idx < 0) return name
// Don't strip file paths: drive letters (C:\...), UNC paths (\\server\...), or relative paths (.\, ..\)
if (
/^[A-Za-z]:/.test(name) ||
name.startsWith('\\\\') ||
name.startsWith('.\\') ||
name.startsWith('..\\')
)
return name
return name.substring(idx + 1)
}
/** Transform a raw CommandAst pipeline element into ParsedCommandElement */
// exported for testing
export function transformCommandAst(
raw: RawPipelineElement,
): ParsedCommandElement {
const cmdElements = ensureArray(raw.commandElements)
let name = ''
const args: string[] = []
const elementTypes: CommandElementType[] = []
const children: (CommandElementChild[] | undefined)[] = []
let hasChildren = false
// SECURITY: nameType MUST be computed from the raw name (before
// stripModulePrefix). classifyCommandName('scripts\\Get-Process') returns
// 'application' (contains \\) — the correct answer, since PowerShell resolves
// this as a file path. After stripping it becomes 'Get-Process' which
// classifies as 'cmdlet' — wrong, and allowlist checks would trust it.
// Auto-allow paths gate on nameType !== 'application' to catch this.
// name (stripped) is still used for deny-rule matching symmetry, which is
// fail-safe: deny rules over-match (Module\\Remove-Item still hits a
// Remove-Item deny), allow rules are separately gated by nameType.
let nameType: 'cmdlet' | 'application' | 'unknown' = 'unknown'
if (cmdElements.length > 0) {
const first = cmdElements[0]!
// SECURITY: only trust .value for string-literal element types with a
// string-typed value. Numeric ConstantExpressionAst (e.g. `& 1`) emits an
// integer .value that crashes stripModulePrefix() → parser falls through
// to passthrough. For non-string-literal or non-string .value, use .text.
const isFirstStringLiteral =
first.type === 'StringConstantExpressionAst' ||
first.type === 'ExpandableStringExpressionAst'
const rawNameUnstripped =
isFirstStringLiteral && typeof first.value === 'string'
? first.value
: first.text
// SECURITY: strip surrounding quotes from the command name. When .value is
// unavailable (no StaticType on the raw node), .text preserves quotes —
// `& 'Invoke-Expression' 'x'` yields "'Invoke-Expression'". Stripping here
// at the source means every downstream reader of element.name (deny-rule
// matching, GIT_SAFETY_WRITE_CMDLETS lookup, resolveToCanonical, etc.)
// sees the bare cmdlet name. No-op when .value already stripped.
const rawName = rawNameUnstripped.replace(/^['"]|['"]$/g, '')
// SECURITY: PowerShell built-in cmdlet names are ASCII-only. Non-ASCII
// characters in cmdlet position are inherently suspicious — .NET
// OrdinalIgnoreCase folds U+017F (ſ) → S and U+0131 (ı) → I per
// UnicodeData.txt SimpleUppercaseMapping, so PowerShell resolves
// `ſtart-proceſſ` → Start-Process at runtime. JS .toLowerCase() does NOT
// fold these (ſ is already lowercase), so every downstream name
// comparison (NEVER_SUGGEST, deny-rule strEquals, resolveToCanonical,
// security validators) misses. Force 'application' to gate auto-allow
// (blocks at the nameType !== 'application' checks). Finding #31.
// Verified on Windows (pwsh 7.x, 2026-03): ſtart-proceſſ does NOT resolve.
// Retained as defense-in-depth against future .NET/PS behavior changes
// or module-provided command resolution hooks.
if (/[\u0080-\uFFFF]/.test(rawName)) {
nameType = 'application'
} else {
nameType = classifyCommandName(rawName)
}
name = stripModulePrefix(rawName)
elementTypes.push(mapElementType(first.type, first.expressionType))
for (let i = 1; i < cmdElements.length; i++) {
const ce = cmdElements[i]!
// Use resolved .value for string constants (strips quotes, resolves
// backtick escapes like `n -> newline) but keep raw .text for parameters
// (where .value loses the dash prefix, e.g. '-Path' -> 'Path'),
// variables, and other non-string types.
const isStringLiteral =
ce.type === 'StringConstantExpressionAst' ||
ce.type === 'ExpandableStringExpressionAst'
args.push(isStringLiteral && ce.value != null ? ce.value : ce.text)
elementTypes.push(mapElementType(ce.type, ce.expressionType))
// Map raw children (CommandParameterAst.Argument) through
// mapElementType so consumers see 'Variable', 'StringConstant', etc.
const rawChildren = ensureArray(ce.children)
if (rawChildren.length > 0) {
hasChildren = true
children.push(
rawChildren.map(c => ({
type: mapElementType(c.type),
text: c.text,
})),
)
} else {
children.push(undefined)
}
}
}
const result: ParsedCommandElement = {
name,
nameType,
elementType: 'CommandAst',
args,
text: raw.text,
elementTypes,
...(hasChildren ? { children } : {}),
}
// Preserve redirections from nested commands (e.g., in && / || chains)
const rawRedirs = ensureArray(raw.redirections)
if (rawRedirs.length > 0) {
result.redirections = rawRedirs.map(transformRedirection)
}
return result
}
/** Transform a non-CommandAst pipeline element into ParsedCommandElement */
// exported for testing
export function transformExpressionElement(
raw: RawPipelineElement,
): ParsedCommandElement {
const elementType: PipelineElementType =
raw.type === 'ParenExpressionAst'
? 'ParenExpressionAst'
: 'CommandExpressionAst'
const elementTypes: CommandElementType[] = [
mapElementType(raw.type, raw.expressionType),
]
return {
name: raw.text,
nameType: 'unknown',
elementType,
args: [],
text: raw.text,
elementTypes,
}
}
/** Map raw redirection to ParsedRedirection */
// exported for testing
export function transformRedirection(raw: RawRedirection): ParsedRedirection {
if (raw.type === 'MergingRedirectionAst') {
return { operator: '2>&1', target: '', isMerging: true }
}
const append = raw.append ?? false
const fromStream = raw.fromStream ?? 'Output'
let operator: ParsedRedirection['operator']
if (append) {
switch (fromStream) {
case 'Error':
operator = '2>>'
break
case 'All':
operator = '*>>'
break
default:
operator = '>>'
break
}
} else {
switch (fromStream) {
case 'Error':
operator = '2>'
break
case 'All':
operator = '*>'
break
default:
operator = '>'
break
}
}
return { operator, target: raw.locationText ?? '', isMerging: false }
}
/** Transform a raw statement into ParsedStatement */