-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcli.ts
More file actions
1350 lines (1220 loc) · 46.2 KB
/
cli.ts
File metadata and controls
1350 lines (1220 loc) · 46.2 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
#!/usr/bin/env node
import { Command } from 'commander';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
import { isIPv6 } from 'net';
import { WrapperConfig, LogLevel, RateLimitConfig } from './types';
import { logger } from './logger';
import {
writeConfigs,
startContainers,
runAgentCommand,
stopContainers,
cleanup,
} from './docker-manager';
import {
ensureFirewallNetwork,
setupHostIptables,
cleanupHostIptables,
} from './host-iptables';
import { runMainWorkflow } from './cli-workflow';
import { redactSecrets } from './redact-secrets';
import { validateDomainOrPattern } from './domain-patterns';
import { OutputFormat } from './types';
import { version } from '../package.json';
/**
* Parses a comma-separated list of domains into an array of trimmed, non-empty domain strings
* @param input - Comma-separated domain string (e.g., "github.com, api.github.com, npmjs.org")
* @returns Array of trimmed domain strings with empty entries filtered out
*/
export function parseDomains(input: string): string[] {
return input
.split(',')
.map(d => d.trim())
.filter(d => d.length > 0);
}
/**
* Parses domains from a file, supporting both line-separated and comma-separated formats
* @param filePath - Path to file containing domains (one per line or comma-separated)
* @returns Array of trimmed domain strings with empty entries and comments filtered out
* @throws Error if file doesn't exist or can't be read
*/
export function parseDomainsFile(filePath: string): string[] {
if (!fs.existsSync(filePath)) {
throw new Error(`Domains file not found: ${filePath}`);
}
const content = fs.readFileSync(filePath, 'utf-8');
const domains: string[] = [];
// Split by lines first
const lines = content.split('\n');
for (const line of lines) {
// Remove comments (anything after #)
const withoutComment = line.split('#')[0].trim();
// Skip empty lines
if (withoutComment.length === 0) {
continue;
}
// Check if line contains commas (comma-separated format)
if (withoutComment.includes(',')) {
// Parse as comma-separated domains
const commaSeparated = parseDomains(withoutComment);
domains.push(...commaSeparated);
} else {
// Single domain per line
domains.push(withoutComment);
}
}
return domains;
}
/**
* Default DNS servers (Google Public DNS)
*/
export const DEFAULT_DNS_SERVERS = ['8.8.8.8', '8.8.4.4'];
/**
* Validates that a string is a valid IPv4 address
* @param ip - String to validate
* @returns true if the string is a valid IPv4 address
*/
export function isValidIPv4(ip: string): boolean {
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
return ipv4Regex.test(ip);
}
/**
* Validates that a string is a valid IPv6 address using Node.js built-in net module
* @param ip - String to validate
* @returns true if the string is a valid IPv6 address
*/
export function isValidIPv6(ip: string): boolean {
return isIPv6(ip);
}
/**
* Pre-defined agent image presets
*/
export const AGENT_IMAGE_PRESETS = ['default', 'act'] as const;
/**
* Safe patterns for custom agent base images to prevent supply chain attacks.
* Allows:
* - Official Ubuntu images (ubuntu:XX.XX)
* - catthehacker runner images (ghcr.io/catthehacker/ubuntu:runner-XX.XX, full-XX.XX, or act-XX.XX)
* - Images with SHA256 digest pinning
*/
const SAFE_BASE_IMAGE_PATTERNS = [
// Official Ubuntu images (e.g., ubuntu:22.04, ubuntu:24.04)
/^ubuntu:\d+\.\d+$/,
// catthehacker runner images (e.g., ghcr.io/catthehacker/ubuntu:runner-22.04, act-24.04)
/^ghcr\.io\/catthehacker\/ubuntu:(runner|full|act)-\d+\.\d+$/,
// catthehacker images with SHA256 digest pinning
/^ghcr\.io\/catthehacker\/ubuntu:(runner|full|act)-\d+\.\d+@sha256:[a-f0-9]{64}$/,
// Official Ubuntu images with SHA256 digest pinning
/^ubuntu:\d+\.\d+@sha256:[a-f0-9]{64}$/,
];
/**
* Checks if the given value is a preset name (default, act)
*/
export function isAgentImagePreset(value: string | undefined): value is 'default' | 'act' {
return value === 'default' || value === 'act';
}
/**
* Validates that an agent image value is either a preset or an approved custom base image.
* For presets ('default', 'act'), validation always passes.
* For custom images, validates against approved patterns to prevent supply chain attacks.
* @param image - Agent image value (preset or custom image reference)
* @returns Object with valid boolean and optional error message
*/
export function validateAgentImage(image: string): { valid: boolean; error?: string } {
// Presets are always valid
if (isAgentImagePreset(image)) {
return { valid: true };
}
// Check custom images against safe patterns
const isValid = SAFE_BASE_IMAGE_PATTERNS.some(pattern => pattern.test(image));
if (isValid) {
return { valid: true };
}
return {
valid: false,
error: `Invalid agent image: "${image}". ` +
'For security, only approved images are allowed:\n\n' +
' Presets (pre-built, fast):\n' +
' default - Minimal ubuntu:22.04 (~200MB)\n' +
' act - GitHub Actions parity (~2GB)\n\n' +
' Custom base images (requires --build-local):\n' +
' ubuntu:XX.XX (e.g., ubuntu:22.04)\n' +
' ghcr.io/catthehacker/ubuntu:runner-XX.XX\n' +
' ghcr.io/catthehacker/ubuntu:full-XX.XX\n' +
' ghcr.io/catthehacker/ubuntu:act-XX.XX\n\n' +
' Use @sha256:... suffix for digest-pinned versions.'
};
}
/**
* Result of processing the agent image option
*/
export interface AgentImageResult {
/** The resolved agent image value */
agentImage: string;
/** Whether this is a preset (default, act) or custom image */
isPreset: boolean;
/** Log message to display (info level) */
infoMessage?: string;
/** Error message if validation failed */
error?: string;
/** Whether --build-local is required but not provided */
requiresBuildLocal?: boolean;
}
/**
* Processes and validates the agent image option.
* This function handles the logic for determining whether the image is valid,
* whether it requires --build-local, and what messages to display.
*
* @param agentImageOption - The --agent-image option value (may be undefined)
* @param buildLocal - Whether --build-local flag was provided
* @returns AgentImageResult with the processed values
*/
export function processAgentImageOption(
agentImageOption: string | undefined,
buildLocal: boolean
): AgentImageResult {
const agentImage = agentImageOption || 'default';
// Validate the image (works for both presets and custom images)
const validation = validateAgentImage(agentImage);
if (!validation.valid) {
return {
agentImage,
isPreset: false,
error: validation.error,
};
}
const isPreset = isAgentImagePreset(agentImage);
// Custom images (not presets) require --build-local
if (!isPreset) {
if (!buildLocal) {
return {
agentImage,
isPreset: false,
requiresBuildLocal: true,
error: '❌ Custom agent images require --build-local flag\n Example: awf --build-local --agent-image ghcr.io/catthehacker/ubuntu:runner-22.04 ...',
};
}
return {
agentImage,
isPreset: false,
infoMessage: `Using custom agent base image: ${agentImage}`,
};
}
// Handle presets
if (agentImage === 'act') {
return {
agentImage,
isPreset: true,
infoMessage: 'Using agent image preset: act (GitHub Actions parity)',
};
}
// 'default' preset - no special message needed
return {
agentImage,
isPreset: true,
};
}
/**
* Result of validating API proxy configuration
*/
export interface ApiProxyValidationResult {
/** Whether the API proxy should be enabled */
enabled: boolean;
/** Warning messages to display */
warnings: string[];
/** Debug messages to display */
debugMessages: string[];
}
/**
* Validates the API proxy configuration and returns appropriate messages.
* Accepts booleans (not actual keys) to prevent sensitive data from flowing
* through to log output (CodeQL: clear-text logging of sensitive information).
* @param enableApiProxy - Whether --enable-api-proxy flag was provided
* @param hasOpenaiKey - Whether an OpenAI API key is present
* @param hasAnthropicKey - Whether an Anthropic API key is present
* @param hasCopilotKey - Whether a GitHub Copilot API key is present
* @returns ApiProxyValidationResult with warnings and debug messages
*/
export function validateApiProxyConfig(
enableApiProxy: boolean,
hasOpenaiKey?: boolean,
hasAnthropicKey?: boolean,
hasCopilotKey?: boolean
): ApiProxyValidationResult {
if (!enableApiProxy) {
return { enabled: false, warnings: [], debugMessages: [] };
}
const warnings: string[] = [];
const debugMessages: string[] = [];
if (!hasOpenaiKey && !hasAnthropicKey && !hasCopilotKey) {
warnings.push('⚠️ API proxy enabled but no API keys found in environment');
warnings.push(' Set OPENAI_API_KEY, ANTHROPIC_API_KEY, or COPILOT_GITHUB_TOKEN to use the proxy');
}
if (hasOpenaiKey) {
debugMessages.push('OpenAI API key detected - will be held securely in sidecar');
}
if (hasAnthropicKey) {
debugMessages.push('Anthropic API key detected - will be held securely in sidecar');
}
if (hasCopilotKey) {
debugMessages.push('GitHub Copilot API key detected - will be held securely in sidecar');
}
return { enabled: true, warnings, debugMessages };
}
/**
* Builds a RateLimitConfig from parsed CLI options.
*/
export function buildRateLimitConfig(options: {
rateLimit?: boolean;
rateLimitRpm?: string;
rateLimitRph?: string;
rateLimitBytesPm?: string;
}): { config: RateLimitConfig } | { error: string } {
// --no-rate-limit explicitly disables (even if other flags are set)
if (options.rateLimit === false) {
return { config: { enabled: false, rpm: 0, rph: 0, bytesPm: 0 } };
}
// Rate limiting is opt-in: disabled unless at least one --rate-limit-* flag is provided
const hasAnyLimit = options.rateLimitRpm !== undefined ||
options.rateLimitRph !== undefined ||
options.rateLimitBytesPm !== undefined;
if (!hasAnyLimit) {
return { config: { enabled: false, rpm: 0, rph: 0, bytesPm: 0 } };
}
// Defaults for any limit not explicitly set
const config: RateLimitConfig = { enabled: true, rpm: 600, rph: 10000, bytesPm: 52428800 };
if (options.rateLimitRpm !== undefined) {
const rpm = parseInt(options.rateLimitRpm, 10);
if (isNaN(rpm) || rpm <= 0) return { error: '--rate-limit-rpm must be a positive integer' };
config.rpm = rpm;
}
if (options.rateLimitRph !== undefined) {
const rph = parseInt(options.rateLimitRph, 10);
if (isNaN(rph) || rph <= 0) return { error: '--rate-limit-rph must be a positive integer' };
config.rph = rph;
}
if (options.rateLimitBytesPm !== undefined) {
const bytesPm = parseInt(options.rateLimitBytesPm, 10);
if (isNaN(bytesPm) || bytesPm <= 0) return { error: '--rate-limit-bytes-pm must be a positive integer' };
config.bytesPm = bytesPm;
}
return { config };
}
/**
* Validates that rate-limit flags are not used without --enable-api-proxy.
*/
export function validateRateLimitFlags(enableApiProxy: boolean, options: {
rateLimit?: boolean;
rateLimitRpm?: string;
rateLimitRph?: string;
rateLimitBytesPm?: string;
}): FlagValidationResult {
if (!enableApiProxy) {
const hasRateLimitFlags = options.rateLimitRpm !== undefined ||
options.rateLimitRph !== undefined ||
options.rateLimitBytesPm !== undefined ||
options.rateLimit === false;
if (hasRateLimitFlags) {
return { valid: false, error: 'Rate limit flags require --enable-api-proxy' };
}
}
return { valid: true };
}
/**
* Result of validating flag combinations
*/
export interface FlagValidationResult {
/** Whether the validation passed */
valid: boolean;
/** Error message if validation failed */
error?: string;
}
/**
* Checks if any rate limit options are set in the CLI options.
* Used to warn when rate limit flags are provided without --enable-api-proxy.
*/
export function hasRateLimitOptions(options: {
rateLimitRpm?: string;
rateLimitRph?: string;
rateLimitBytesPm?: string;
rateLimit?: boolean;
}): boolean {
return !!(options.rateLimitRpm || options.rateLimitRph || options.rateLimitBytesPm || options.rateLimit === false);
}
/**
* Validates that --skip-pull is not used with --build-local
* @param skipPull - Whether --skip-pull flag was provided
* @param buildLocal - Whether --build-local flag was provided
* @returns FlagValidationResult with validation status and error message
*/
export function validateSkipPullWithBuildLocal(
skipPull: boolean | undefined,
buildLocal: boolean | undefined
): FlagValidationResult {
if (skipPull && buildLocal) {
return {
valid: false,
error: '--skip-pull cannot be used with --build-local. Building images requires pulling base images from the registry.',
};
}
return { valid: true };
}
/**
* Parses and validates DNS servers from a comma-separated string
* @param input - Comma-separated DNS server string (e.g., "8.8.8.8,1.1.1.1")
* @returns Array of validated DNS server IP addresses
* @throws Error if any IP address is invalid or if the list is empty
*/
export function parseDnsServers(input: string): string[] {
const servers = input
.split(',')
.map(s => s.trim())
.filter(s => s.length > 0);
if (servers.length === 0) {
throw new Error('At least one DNS server must be specified');
}
for (const server of servers) {
if (!isValidIPv4(server) && !isValidIPv6(server)) {
throw new Error(`Invalid DNS server IP address: ${server}`);
}
}
return servers;
}
/**
* Result of processing the localhost keyword in allowed domains
*/
export interface LocalhostProcessingResult {
/** Updated array of allowed domains with localhost replaced by host.docker.internal */
allowedDomains: string[];
/** Whether the localhost keyword was found and processed */
localhostDetected: boolean;
/** Whether host access should be enabled (if not already enabled) */
shouldEnableHostAccess: boolean;
/** Default port list to use if no custom ports were specified */
defaultPorts?: string;
}
/**
* Processes the localhost keyword in the allowed domains list.
* This function handles the logic for replacing localhost with host.docker.internal,
* preserving protocol prefixes, and determining whether to auto-enable host access
* and default development ports.
*
* @param allowedDomains - Array of allowed domains (may include localhost variants)
* @param enableHostAccess - Whether host access is already enabled
* @param allowHostPorts - Custom host ports if already specified
* @returns LocalhostProcessingResult with the processed values
*/
export function processLocalhostKeyword(
allowedDomains: string[],
enableHostAccess: boolean,
allowHostPorts: string | undefined
): LocalhostProcessingResult {
const localhostIndex = allowedDomains.findIndex(d =>
d === 'localhost' || d === 'http://localhost' || d === 'https://localhost'
);
if (localhostIndex === -1) {
return {
allowedDomains,
localhostDetected: false,
shouldEnableHostAccess: false,
};
}
// Remove localhost and replace with host.docker.internal
const localhostValue = allowedDomains[localhostIndex];
const updatedDomains = [...allowedDomains];
updatedDomains.splice(localhostIndex, 1);
// Preserve protocol if specified
if (localhostValue.startsWith('http://')) {
updatedDomains.push('http://host.docker.internal');
} else if (localhostValue.startsWith('https://')) {
updatedDomains.push('https://host.docker.internal');
} else {
updatedDomains.push('host.docker.internal');
}
return {
allowedDomains: updatedDomains,
localhostDetected: true,
shouldEnableHostAccess: !enableHostAccess,
defaultPorts: allowHostPorts ? undefined : '3000,3001,4000,4200,5000,5173,8000,8080,8081,8888,9000,9090',
};
}
/**
* Escapes a shell argument by wrapping it in single quotes and escaping any single quotes within it
* @param arg - Argument to escape
* @returns Escaped argument safe for shell execution
*/
export function escapeShellArg(arg: string): string {
// If the argument doesn't contain special characters, return as-is
// Character class includes: letters, digits, underscore, dash, dot (literal), slash, equals, colon
if (/^[a-zA-Z0-9_\-./=:]+$/.test(arg)) {
return arg;
}
// Otherwise, wrap in single quotes and escape any single quotes inside
// The pattern '\\'' works by: ending the single-quoted string ('),
// adding an escaped single quote (\'), then starting a new single-quoted string (')
return `'${arg.replace(/'/g, "'\\''")}'`;
}
/**
* Joins an array of shell arguments into a single command string, properly escaping each argument
* @param args - Array of arguments
* @returns Command string with properly escaped arguments
*/
export function joinShellArgs(args: string[]): string {
return args.map(escapeShellArg).join(' ');
}
/**
* Result of parsing environment variables
*/
export interface ParseEnvResult {
success: true;
env: Record<string, string>;
}
export interface ParseEnvError {
success: false;
invalidVar: string;
}
/**
* Result of parsing volume mounts
*/
export interface ParseVolumeMountsResult {
success: true;
mounts: string[];
}
export interface ParseVolumeMountsError {
success: false;
invalidMount: string;
reason: string;
}
/**
* Parses environment variables from an array of KEY=VALUE strings
* @param envVars Array of environment variable strings in KEY=VALUE format
* @returns ParseEnvResult with parsed key-value pairs on success, or ParseEnvError with the invalid variable on failure
*/
export function parseEnvironmentVariables(envVars: string[]): ParseEnvResult | ParseEnvError {
const result: Record<string, string> = {};
for (const envVar of envVars) {
const match = envVar.match(/^([^=]+)=(.*)$/);
if (!match) {
return { success: false, invalidVar: envVar };
}
const [, key, value] = match;
result[key] = value;
}
return { success: true, env: result };
}
/**
* Parses and validates volume mount specifications
* @param mounts Array of volume mount strings in host_path:container_path[:mode] format
* @returns ParseVolumeMountsResult on success, or ParseVolumeMountsError with details on failure
*/
export function parseVolumeMounts(mounts: string[]): ParseVolumeMountsResult | ParseVolumeMountsError {
const result: string[] = [];
for (const mount of mounts) {
// Parse mount specification: host_path:container_path[:mode]
const parts = mount.split(':');
if (parts.length < 2 || parts.length > 3) {
return {
success: false,
invalidMount: mount,
reason: 'Mount must be in format host_path:container_path[:mode]'
};
}
const [hostPath, containerPath, mode] = parts;
// Validate host path is not empty
if (!hostPath || hostPath.trim() === '') {
return {
success: false,
invalidMount: mount,
reason: 'Host path cannot be empty'
};
}
// Validate container path is not empty
if (!containerPath || containerPath.trim() === '') {
return {
success: false,
invalidMount: mount,
reason: 'Container path cannot be empty'
};
}
// Validate host path is absolute
if (!hostPath.startsWith('/')) {
return {
success: false,
invalidMount: mount,
reason: 'Host path must be absolute (start with /)'
};
}
// Validate container path is absolute
if (!containerPath.startsWith('/')) {
return {
success: false,
invalidMount: mount,
reason: 'Container path must be absolute (start with /)'
};
}
// Validate mode if specified
if (mode && mode !== 'ro' && mode !== 'rw') {
return {
success: false,
invalidMount: mount,
reason: 'Mount mode must be either "ro" or "rw"'
};
}
// Validate host path exists
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('fs');
if (!fs.existsSync(hostPath)) {
return {
success: false,
invalidMount: mount,
reason: `Host path does not exist: ${hostPath}`
};
}
} catch (error) {
return {
success: false,
invalidMount: mount,
reason: `Failed to check host path: ${error}`
};
}
// Add to result list
result.push(mount);
}
return { success: true, mounts: result };
}
const program = new Command();
program
.name('awf')
.description('Network firewall for agentic workflows with domain whitelisting')
.version(version)
.option(
'--allow-domains <domains>',
'Comma-separated list of allowed domains. Supports wildcards and protocol prefixes:\n' +
' github.com - exact domain + subdomains (HTTP & HTTPS)\n' +
' *.github.com - any subdomain of github.com\n' +
' api-*.example.com - api-* subdomains\n' +
' https://secure.com - HTTPS only\n' +
' http://legacy.com - HTTP only\n' +
' localhost - auto-configure for local testing (Playwright, etc.)'
)
.option(
'--allow-domains-file <path>',
'Path to file containing allowed domains (one per line or comma-separated, supports # comments)'
)
.option(
'--block-domains <domains>',
'Comma-separated list of blocked domains (takes precedence over allowed domains). Supports wildcards.'
)
.option(
'--block-domains-file <path>',
'Path to file containing blocked domains (one per line or comma-separated, supports # comments)'
)
.option(
'--log-level <level>',
'Log level: debug, info, warn, error',
'info'
)
.option(
'--keep-containers',
'Keep containers running after command exits',
false
)
.option(
'--tty',
'Allocate a pseudo-TTY for the container (required for interactive tools like Claude Code)',
false
)
.option(
'--work-dir <dir>',
'Working directory for temporary files',
path.join(os.tmpdir(), `awf-${Date.now()}`)
)
.option(
'--build-local',
'Build containers locally instead of using GHCR images',
false
)
.option(
'--agent-image <value>',
'Agent container image (default: "default")\n' +
' Presets (pre-built, fast):\n' +
' default - Minimal ubuntu:22.04 (~200MB)\n' +
' act - GitHub Actions parity (~2GB)\n' +
' Custom base images (requires --build-local):\n' +
' ubuntu:XX.XX\n' +
' ghcr.io/catthehacker/ubuntu:runner-XX.XX\n' +
' ghcr.io/catthehacker/ubuntu:full-XX.XX'
)
.option(
'--image-registry <registry>',
'Container image registry',
'ghcr.io/github/gh-aw-firewall'
)
.option(
'--image-tag <tag>',
'Container image tag',
'latest'
)
.option(
'--skip-pull',
'Use local images without pulling from registry (requires images to be pre-downloaded)',
false
)
.option(
'-e, --env <KEY=VALUE>',
'Additional environment variables to pass to container (can be specified multiple times)',
(value, previous: string[] = []) => [...previous, value],
[]
)
.option(
'--env-all',
'Pass all host environment variables to container (excludes system vars like PATH)',
false
)
.option(
'-v, --mount <host_path:container_path[:mode]>',
'Volume mount (can be specified multiple times). Format: host_path:container_path[:ro|rw]',
(value, previous: string[] = []) => [...previous, value],
[]
)
.option(
'--container-workdir <dir>',
'Working directory inside the container (should match GITHUB_WORKSPACE for path consistency)'
)
.option(
'--dns-servers <servers>',
'Comma-separated list of trusted DNS servers. DNS traffic is ONLY allowed to these servers (default: 8.8.8.8,8.8.4.4)',
'8.8.8.8,8.8.4.4'
)
.option(
'--proxy-logs-dir <path>',
'Directory to save Squid proxy logs to (writes access.log directly to this directory)'
)
.option(
'--enable-host-access',
'Enable access to host services via host.docker.internal. ' +
'Security warning: When combined with --allow-domains host.docker.internal, ' +
'containers can access ANY service on the host machine.',
false
)
.option(
'--allow-host-ports <ports>',
'Comma-separated list of ports or port ranges to allow when using --enable-host-access. ' +
'By default, only ports 80 and 443 are allowed. ' +
'Example: --allow-host-ports 3000 or --allow-host-ports 3000,8080 or --allow-host-ports 3000-3010,8000-8090'
)
.option(
'--ssl-bump',
'Enable SSL Bump for HTTPS content inspection (allows URL path filtering for HTTPS)',
false
)
.option(
'--allow-urls <urls>',
'Comma-separated list of allowed URL patterns for HTTPS (requires --ssl-bump).\n' +
' Supports wildcards: https://github.com/myorg/*'
)
.option(
'--enable-api-proxy',
'Enable API proxy sidecar for holding authentication credentials.\n' +
' Deploys a Node.js proxy that injects API keys securely.\n' +
' Supports OpenAI (Codex) and Anthropic (Claude) APIs.',
false
)
.option(
'--copilot-api-target <host>',
'Target hostname for GitHub Copilot API requests in the api-proxy sidecar.\n' +
' Defaults to api.githubcopilot.com. Useful for GHES deployments.\n' +
' Can also be set via COPILOT_API_TARGET env var.',
)
.option(
'--rate-limit-rpm <n>',
'Enable rate limiting: max requests per minute per provider (requires --enable-api-proxy)',
)
.option(
'--rate-limit-rph <n>',
'Enable rate limiting: max requests per hour per provider (requires --enable-api-proxy)',
)
.option(
'--rate-limit-bytes-pm <n>',
'Enable rate limiting: max request bytes per minute per provider (requires --enable-api-proxy)',
)
.option(
'--no-rate-limit',
'Explicitly disable rate limiting in the API proxy (requires --enable-api-proxy)',
)
.argument('[args...]', 'Command and arguments to execute (use -- to separate from options)')
.action(async (args: string[], options) => {
// Require -- separator for passing command arguments
if (args.length === 0) {
console.error('Error: No command specified. Use -- to separate command from options.');
console.error('Example: awf --allow-domains github.com -- curl https://api.github.com');
process.exit(1);
}
// Command argument handling:
//
// SINGLE ARGUMENT (complete shell command):
// When a single argument is passed, it's treated as a complete shell
// command string. This is CRITICAL for preserving shell variables ($HOME,
// $(command), etc.) that must expand in the container, not on the host.
//
// Example: awf -- 'echo $HOME'
// → args = ['echo $HOME'] (single element)
// → Passed as-is: 'echo $HOME'
// → Docker Compose: 'echo $$HOME' (escaped for YAML)
// → Container shell: 'echo $HOME' (expands to container home)
//
// MULTIPLE ARGUMENTS (shell-parsed by user's shell):
// When multiple arguments are passed, each is shell-escaped and joined.
// This happens when the user doesn't quote the command.
//
// Example: awf -- curl -H "Auth: token" https://api.github.com
// → args = ['curl', '-H', 'Auth: token', 'https://api.github.com']
// → joinShellArgs(): curl -H 'Auth: token' https://api.github.com
//
// Why not use shell-quote library?
// - shell-quote expands variables on the HOST ($HOME → /home/hostuser)
// - We need variables to expand in CONTAINER ($HOME → /root or /home/runner)
// - The $$$$ escaping pattern requires literal $ preservation
//
const agentCommand = args.length === 1 ? args[0] : joinShellArgs(args);
// Parse and validate options
const logLevel = options.logLevel as LogLevel;
if (!['debug', 'info', 'warn', 'error'].includes(logLevel)) {
console.error(`Invalid log level: ${logLevel}`);
process.exit(1);
}
logger.setLevel(logLevel);
// Parse domains from both --allow-domains flag and --allow-domains-file
let allowedDomains: string[] = [];
// Parse domains from command-line flag if provided
if (options.allowDomains) {
allowedDomains = parseDomains(options.allowDomains);
}
// Parse domains from file if provided
if (options.allowDomainsFile) {
try {
const fileDomainsArray = parseDomainsFile(options.allowDomainsFile);
allowedDomains.push(...fileDomainsArray);
} catch (error) {
logger.error(`Failed to read domains file: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
}
// Log when no domains are specified (all network access will be blocked)
if (allowedDomains.length === 0) {
logger.debug('No allowed domains specified - all network access will be blocked');
}
// Remove duplicates (in case domains appear in both sources)
allowedDomains = [...new Set(allowedDomains)];
// Handle special "localhost" keyword for Playwright testing
// This makes localhost testing work out of the box without requiring manual configuration
const localhostResult = processLocalhostKeyword(
allowedDomains,
options.enableHostAccess || false,
options.allowHostPorts
);
if (localhostResult.localhostDetected) {
allowedDomains = localhostResult.allowedDomains;
// Auto-enable host access
if (localhostResult.shouldEnableHostAccess) {
options.enableHostAccess = true;
logger.warn('⚠️ Security warning: localhost keyword enables host access - agent can reach services on your machine');
logger.info('ℹ️ localhost keyword detected - automatically enabling host access');
}
// Auto-configure common dev ports if not already specified
if (localhostResult.defaultPorts) {
options.allowHostPorts = localhostResult.defaultPorts;
logger.info('ℹ️ localhost keyword detected - allowing common development ports (3000, 4200, 5173, 8080, etc.)');
logger.info(' Use --allow-host-ports to customize the port list');
}
}
// Validate all domains and patterns
for (const domain of allowedDomains) {
try {
validateDomainOrPattern(domain);
} catch (error) {
logger.error(`Invalid domain or pattern: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
}
// Parse blocked domains from both --block-domains flag and --block-domains-file
let blockedDomains: string[] = [];
// Parse blocked domains from command-line flag if provided
if (options.blockDomains) {
blockedDomains = parseDomains(options.blockDomains);
}
// Parse blocked domains from file if provided
if (options.blockDomainsFile) {
try {
const fileBlockedDomainsArray = parseDomainsFile(options.blockDomainsFile);
blockedDomains.push(...fileBlockedDomainsArray);
} catch (error) {
logger.error(`Failed to read blocked domains file: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
}
// Remove duplicates from blocked domains
blockedDomains = [...new Set(blockedDomains)];
// Validate all blocked domains and patterns
for (const domain of blockedDomains) {
try {
validateDomainOrPattern(domain);
} catch (error) {
logger.error(`Invalid blocked domain or pattern: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
}
// Parse additional environment variables from --env flags
let additionalEnv: Record<string, string> = {};
if (options.env && Array.isArray(options.env)) {
const parsed = parseEnvironmentVariables(options.env);
if (!parsed.success) {
logger.error(`Invalid environment variable format: ${parsed.invalidVar} (expected KEY=VALUE)`);
process.exit(1);
}
additionalEnv = parsed.env;
}
// Parse and validate volume mounts from --mount flags
let volumeMounts: string[] | undefined = undefined;
if (options.mount && Array.isArray(options.mount) && options.mount.length > 0) {
const parsed = parseVolumeMounts(options.mount);
if (!parsed.success) {
logger.error(`Invalid volume mount: ${parsed.invalidMount}`);
logger.error(`Reason: ${parsed.reason}`);
process.exit(1);
}
volumeMounts = parsed.mounts;
logger.debug(`Parsed ${volumeMounts.length} volume mount(s)`);
}
// Parse and validate DNS servers
let dnsServers: string[];
try {
dnsServers = parseDnsServers(options.dnsServers);
} catch (error) {
logger.error(`Invalid DNS servers: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
// Parse --allow-urls for SSL Bump mode
let allowedUrls: string[] | undefined;
if (options.allowUrls) {
allowedUrls = parseDomains(options.allowUrls);
if (allowedUrls.length > 0 && !options.sslBump) {
logger.error('--allow-urls requires --ssl-bump to be enabled');