-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapproval-policy.ts
More file actions
2278 lines (2117 loc) · 69.7 KB
/
approval-policy.ts
File metadata and controls
2278 lines (2117 loc) · 69.7 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 { createHash, randomUUID } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { URL } from 'node:url';
import YAML from 'yaml';
import type {
NetworkPolicyAction,
NetworkRule,
} from '../shared/network-policy.js';
import {
asRecord,
DEFAULT_NETWORK_DEFAULT,
DEFAULT_NETWORK_RULES,
doesNetworkHostPatternExpandToSubdomains,
normalizeNetworkAgent,
normalizeNetworkHostScope,
normalizeNetworkPathPattern,
normalizeNetworkPort,
readNetworkPolicyState,
} from '../shared/network-policy.js';
import { classifyMcpTool } from './mcp/tool-classifier.js';
import { WORKSPACE_ROOT, WORKSPACE_ROOT_DISPLAY } from './runtime-paths.js';
import type { ChatMessage } from './types.js';
export type {
NetworkPolicyAction,
NetworkRule,
} from '../shared/network-policy.js';
export {
DEFAULT_NETWORK_DEFAULT,
DEFAULT_NETWORK_RULES,
normalizeNetworkRule,
} from '../shared/network-policy.js';
export type ApprovalTier = 'green' | 'yellow' | 'red';
export type ApprovalDecision =
| 'auto'
| 'implicit'
| 'approved_once'
| 'approved_session'
| 'approved_agent'
| 'approved_all'
| 'approved_fullauto'
| 'promoted'
| 'required'
| 'denied';
export interface ApprovalPolicyRule {
pattern?: string;
paths?: string[];
tools?: string[];
}
export interface ApprovalPolicyConfig {
pinnedRed: ApprovalPolicyRule[];
networkDefault: NetworkPolicyAction;
networkRules: NetworkRule[];
networkPresets: string[];
workspaceFence: boolean;
maxPendingApprovals: number;
approvalTimeoutSecs: number;
audit: {
logAllRed: boolean;
logDenials: boolean;
};
}
interface ClassifiedAction {
tier: ApprovalTier;
actionKey: string;
intent: string;
consequenceIfDenied: string;
reason: string;
commandPreview: string;
pathHints: string[];
hostHints: string[];
writeIntent: boolean;
promotableRed: boolean;
stickyYellow: boolean;
hardDeny?: boolean;
}
interface PendingApproval {
id: string;
fingerprint: string;
actionKey: string;
toolName: string;
intent: string;
consequenceIfDenied: string;
reason: string;
commandPreview: string;
createdAtMs: number;
expiresAtMs: number;
originalPrompt: string;
pinned: boolean;
}
export interface ApprovalPrelude {
immediateMessage?: string;
replayPrompt?: string;
approvalMode?: ApprovalMode;
approvedRequestId?: string;
}
export interface ToolApprovalEvaluation {
baseTier: ApprovalTier;
tier: ApprovalTier;
decision: ApprovalDecision;
actionKey: string;
fingerprint: string;
requestId?: string;
expiresAtMs?: number;
intent: string;
consequenceIfDenied: string;
reason: string;
commandPreview: string;
pinned: boolean;
implicitDelayMs?: number;
hostHints: string[];
}
const WORKSPACE_ROOT_ACTUAL = WORKSPACE_ROOT;
const POLICY_PATH = path.join(
WORKSPACE_ROOT_ACTUAL,
'.hybridclaw',
'policy.yaml',
);
const AGENT_TRUST_STORE_PATH = path.join(
WORKSPACE_ROOT_ACTUAL,
'.hybridclaw',
'approval-agent-trust.json',
);
const APPROVAL_MODES = ['once', 'session', 'agent', 'all'] as const;
type ApprovalMode = (typeof APPROVAL_MODES)[number];
const TRUST_STORE_PATH = path.join(
WORKSPACE_ROOT_ACTUAL,
'approval-trust.json',
);
const LEGACY_AGENT_TRUST_STORE_PATH = path.join(
WORKSPACE_ROOT_ACTUAL,
'.hybridclaw',
'approval-trust.json',
);
const AGENT_ID_ENV = 'HYBRIDCLAW_AGENT_ID';
const YELLOW_IMPLICIT_DELAY_MS = 5_000;
const YELLOW_IMPLICIT_DELAY_SECS = Math.max(
1,
Math.round(YELLOW_IMPLICIT_DELAY_MS / 1_000),
);
const IMPLICIT_DELAY_BROWSER_INPUT_TOOLS = new Set([
'browser_press',
'browser_type',
'browser_upload',
]);
const MAX_PROMPT_CHARS = 1_200;
const MAX_COMMAND_PREVIEW_CHARS = 160;
const SCRATCH_ROOTS = Array.from(
new Set(
['/tmp', '/private/tmp', os.tmpdir()]
.map((value) => value.trim())
.filter(Boolean)
.map((value) => path.resolve(value)),
),
);
export const DEFAULT_POLICY: ApprovalPolicyConfig = {
pinnedRed: [
{ pattern: 'rm\\s+-rf\\s+/' },
{ paths: ['~/.ssh/**', '/etc/**', '.env*'] },
{ tools: ['force_push'] },
],
networkDefault: DEFAULT_NETWORK_DEFAULT,
networkRules: DEFAULT_NETWORK_RULES,
networkPresets: [],
workspaceFence: true,
maxPendingApprovals: 3,
approvalTimeoutSecs: 120,
audit: {
logAllRed: true,
logDenials: true,
},
};
const CRITICAL_BASH_RE =
/\b(sudo|mkfs(?:\.[a-z0-9_+-]+)?|shutdown|reboot|poweroff)\b|:\(\)\s*\{.*\};\s*:|\bchmod\s+777\b|\bcurl\b[^\n|]*\|\s*(sh|bash|zsh)\b|\bwget\b[^\n|]*\|\s*(sh|bash|zsh)\b/i;
const FORCE_PUSH_RE = /\bgit\s+push\s+--force(?:-with-lease)?\b/i;
const DELETE_RE = /\brm\s+-[^\n;|&]*\b|\bfind\b[^\n]*\s-delete\b/i;
const WRITE_INTENT_RE =
/\b(mkdir|touch|mv|cp|chmod|chown|tee)\b|(^|[^>])>>?[^>]|sed\s+-i|perl\s+-pi/i;
const INSTALL_RE =
/\b(?:npm|pnpm|yarn|bun)\s+(?:install|add)\b|\b(?:pip|pip3)\s+install\b|\bpython(?:3)?\s+-m\s+pip\s+install\b|\buv\s+pip\s+install\b/i;
const GIT_WRITE_RE =
/\bgit\s+(add|commit|checkout\s+-b|branch|merge|rebase|tag)\b/i;
const UNKNOWN_SCRIPT_RE =
/(^|\s)(\.[/\\][^\s]+|bash\s+[^\s]+\.sh|zsh\s+[^\s]+\.sh|sh\s+[^\s]+\.sh)(\s|$)/i;
const READ_ONLY_PDF_SCRIPT_RE =
/^\s*node\s+skills\/pdf\/scripts\/(?:extract_pdf_text|check_fillable_fields|extract_form_field_info|extract_form_structure)\.mjs\b/i;
const READ_ONLY_BASH_RE =
/^\s*(ls|pwd|cat|head|tail|wc|rg|grep|find|git\s+(status|log|diff|show)|npm\s+test|pnpm\s+test|yarn\s+test|vitest|pytest|phpunit|node\s+--version|npm\s+--version|pnpm\s+--version|yarn\s+--version)\b/i;
const NETWORK_COMMAND_RE = /\b(curl|wget|http|https|ssh|scp)\b/i;
const ABS_PATH_RE = /(^|\s)(\/[^\s"'`;,|&()<>]+)/g;
const URL_RE = /https?:\/\/[^\s"'`<>]+/gi;
const HOST_RE =
/\b(?:ssh|scp)\s+[^\s@]*@?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(?::\S+)?/g;
const APPROVE_RE =
/^(?:\/?(?:approve|yes|y))(?:\s+([a-f0-9-]{6,64}))?(?:\s+(for\s+session|session|for\s+all|all|for\s+agent|agent))?$/i;
const DENY_RE = /^(?:\/?(?:deny|reject|skip|no|n))(?:\s+([a-f0-9-]{6,64}))?$/i;
function isVoiceChannelId(value: string | undefined): boolean {
return String(value || '')
.trim()
.toLowerCase()
.startsWith('voice:');
}
function normalizeText(value: unknown): string {
return String(value || '')
.replace(/\s+/g, ' ')
.trim();
}
function normalizePrompt(value: string): string {
return normalizeText(value).slice(0, MAX_PROMPT_CHARS);
}
function normalizePreview(value: string): string {
const clean = normalizeText(value);
if (!clean) return '(no command preview)';
return clean.length > MAX_COMMAND_PREVIEW_CHARS
? `${clean.slice(0, MAX_COMMAND_PREVIEW_CHARS - 1)}...`
: clean;
}
function stableHash(input: string): string {
return createHash('sha256').update(input).digest('hex').slice(0, 16);
}
function parseJsonObject(raw: string): Record<string, unknown> {
try {
const parsed = JSON.parse(raw) as unknown;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
// ignore
}
return {};
}
function normalizeBooleanValue(raw: unknown, fallback: boolean): boolean {
if (typeof raw === 'boolean') return raw;
if (typeof raw !== 'string') return fallback;
const normalized = raw.trim().toLowerCase();
if (normalized === 'true') return true;
if (normalized === 'false') return false;
return fallback;
}
function normalizeIntegerValue(raw: unknown, fallback: number): number {
if (typeof raw === 'number' && Number.isFinite(raw)) {
return Math.trunc(raw);
}
if (typeof raw !== 'string') return fallback;
const parsed = Number.parseInt(raw.trim(), 10);
return Number.isFinite(parsed) ? parsed : fallback;
}
function normalizeStringList(raw: unknown): string[] {
if (Array.isArray(raw)) {
return raw.map((entry) => String(entry || '').trim()).filter(Boolean);
}
if (typeof raw === 'string') {
return raw
.split(',')
.map((entry) => entry.trim())
.filter(Boolean);
}
return [];
}
function normalizeApprovalRule(raw: unknown): ApprovalPolicyRule | null {
const rule = asRecord(raw);
const pattern = String(rule.pattern || '').trim();
const tools = normalizeStringList(rule.tools);
const paths = normalizeStringList(rule.paths);
if (!pattern && tools.length === 0 && paths.length === 0) {
return null;
}
return {
...(pattern ? { pattern } : {}),
...(tools.length > 0 ? { tools } : {}),
...(paths.length > 0 ? { paths } : {}),
};
}
function globPatternToRegExp(pattern: string): RegExp {
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*\*/g, '::DOUBLE_STAR::')
.replace(/\*/g, '[^/]*')
.replace(/::DOUBLE_STAR::/g, '.*');
return new RegExp(`^${escaped}$`, 'i');
}
function normalizePathValue(rawPath: string): string {
const value = rawPath.trim().replace(/\\/g, '/');
const withoutWorkspace = value.startsWith('/workspace/')
? value.slice('/workspace/'.length)
: value;
return withoutWorkspace.replace(/^\.\/+/, '').replace(/^\/+/, '');
}
function matchesPathPattern(candidatePath: string, pattern: string): boolean {
const normalizedCandidate = normalizePathValue(candidatePath);
const normalizedPattern = pattern.trim().replace(/\\/g, '/');
if (!normalizedPattern) return false;
// Relative patterns (e.g. ".env*") should match both root and any nested path.
if (
!normalizedPattern.startsWith('/') &&
!normalizedPattern.startsWith('~/')
) {
const relRe = globPatternToRegExp(normalizedPattern.replace(/^\.\//, ''));
if (relRe.test(normalizedCandidate)) return true;
const basename = path.posix.basename(normalizedCandidate);
if (relRe.test(basename)) return true;
return false;
}
const absoluteCandidate = candidatePath.trim().replace(/\\/g, '/');
const absoluteRe = globPatternToRegExp(normalizedPattern);
return absoluteRe.test(absoluteCandidate);
}
export function parsePolicyYaml(raw: string): Partial<ApprovalPolicyConfig> {
const document = asRecord(YAML.parse(raw) as unknown);
const approval = asRecord(document.approval);
const audit = asRecord(document.audit);
const pinnedRed = Array.isArray(approval.pinned_red)
? approval.pinned_red
.map((rule) => normalizeApprovalRule(rule))
.filter((rule): rule is ApprovalPolicyRule => Boolean(rule))
: [];
const networkState = readNetworkPolicyState(document);
return {
...(pinnedRed.length > 0 ? { pinnedRed } : {}),
networkDefault: networkState.defaultAction,
networkRules: networkState.rules.map((rule) => ({
...rule,
methods: [...rule.methods],
paths: [...rule.paths],
})),
networkPresets: [...networkState.presets],
workspaceFence: normalizeBooleanValue(
approval.workspace_fence,
DEFAULT_POLICY.workspaceFence,
),
maxPendingApprovals: Math.max(
1,
normalizeIntegerValue(
approval.max_pending_approvals,
DEFAULT_POLICY.maxPendingApprovals,
),
),
approvalTimeoutSecs: Math.max(
5,
normalizeIntegerValue(
approval.approval_timeout_secs,
DEFAULT_POLICY.approvalTimeoutSecs,
),
),
audit: {
logAllRed: normalizeBooleanValue(
audit.log_all_red,
DEFAULT_POLICY.audit.logAllRed,
),
logDenials: normalizeBooleanValue(
audit.log_denials,
DEFAULT_POLICY.audit.logDenials,
),
},
};
}
export function loadPolicyFromDisk(policyPath: string): ApprovalPolicyConfig {
let filePolicy: Partial<ApprovalPolicyConfig> = {};
try {
if (fs.existsSync(policyPath)) {
const raw = fs.readFileSync(policyPath, 'utf-8');
filePolicy = parsePolicyYaml(raw);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(
`[approval-policy] failed to load policy from ${policyPath}: ${message}`,
);
filePolicy = {};
}
return {
pinnedRed:
Array.isArray(filePolicy.pinnedRed) && filePolicy.pinnedRed.length > 0
? filePolicy.pinnedRed
: DEFAULT_POLICY.pinnedRed,
networkDefault:
filePolicy.networkDefault === 'allow' ||
filePolicy.networkDefault === 'deny'
? filePolicy.networkDefault
: DEFAULT_POLICY.networkDefault,
networkRules: Array.isArray(filePolicy.networkRules)
? filePolicy.networkRules.map((rule) => ({
...rule,
methods: [...rule.methods],
paths: [...rule.paths],
}))
: DEFAULT_POLICY.networkRules.map((rule) => ({
...rule,
methods: [...rule.methods],
paths: [...rule.paths],
})),
networkPresets: Array.isArray(filePolicy.networkPresets)
? [...filePolicy.networkPresets]
: [],
workspaceFence:
typeof filePolicy.workspaceFence === 'boolean'
? filePolicy.workspaceFence
: DEFAULT_POLICY.workspaceFence,
maxPendingApprovals:
typeof filePolicy.maxPendingApprovals === 'number'
? Math.max(1, filePolicy.maxPendingApprovals)
: DEFAULT_POLICY.maxPendingApprovals,
approvalTimeoutSecs:
typeof filePolicy.approvalTimeoutSecs === 'number'
? Math.max(5, filePolicy.approvalTimeoutSecs)
: DEFAULT_POLICY.approvalTimeoutSecs,
audit: {
logAllRed:
typeof filePolicy.audit?.logAllRed === 'boolean'
? filePolicy.audit.logAllRed
: DEFAULT_POLICY.audit.logAllRed,
logDenials:
typeof filePolicy.audit?.logDenials === 'boolean'
? filePolicy.audit.logDenials
: DEFAULT_POLICY.audit.logDenials,
},
};
}
function latestUserMessageText(messages: ChatMessage[]): string {
for (let i = messages.length - 1; i >= 0; i -= 1) {
if (messages[i].role !== 'user') continue;
const content = messages[i].content;
if (typeof content === 'string')
return content.trim().slice(0, MAX_PROMPT_CHARS);
if (!Array.isArray(content)) continue;
const textParts: string[] = [];
for (const part of content) {
if (!part || typeof part !== 'object') continue;
if (part.type !== 'text') continue;
if (typeof part.text !== 'string') continue;
const trimmed = part.text.trim();
if (trimmed) textParts.push(trimmed);
}
if (textParts.length > 0) {
return textParts.join('\n').trim().slice(0, MAX_PROMPT_CHARS);
}
}
return '';
}
function extractHostsFromUrlLikeText(input: string): string[] {
const hosts = new Set<string>();
for (const match of input.matchAll(URL_RE)) {
const raw = match[0];
try {
const parsed = new URL(raw);
if (parsed.hostname) hosts.add(parsed.hostname.toLowerCase());
} catch {
// ignore
}
}
for (const match of input.matchAll(HOST_RE)) {
const host = String(match[1] || '')
.trim()
.toLowerCase();
if (host) hosts.add(host);
}
return [...hosts];
}
export function normalizeHostScope(host: string): string {
return normalizeNetworkHostScope(host);
}
function defaultPortForProtocol(protocol: string): number {
const normalized = protocol.trim().toLowerCase();
if (normalized === 'http:') return 80;
if (normalized === 'https:') return 443;
return 443;
}
function globHostPatternToRegExp(pattern: string): RegExp {
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*');
return new RegExp(`^${escaped}$`, 'i');
}
function matchesHostPattern(pattern: string, candidateHost: string): boolean {
const normalizedPattern = pattern.trim().toLowerCase().replace(/\.$/, '');
const normalizedCandidate = candidateHost
.trim()
.toLowerCase()
.replace(/\.$/, '');
if (!normalizedPattern || !normalizedCandidate) return false;
if (normalizedPattern === normalizedCandidate) return true;
if (normalizedPattern.includes('*')) {
return globHostPatternToRegExp(normalizedPattern).test(normalizedCandidate);
}
if (
/^\d{1,3}(?:\.\d{1,3}){3}$/.test(normalizedPattern) ||
normalizedPattern.includes(':')
) {
return false;
}
if (doesNetworkHostPatternExpandToSubdomains(normalizedPattern)) {
return normalizeHostScope(normalizedCandidate) === normalizedPattern;
}
return false;
}
function matchesMethodPattern(
allowedMethods: string[],
candidateMethod: string,
): boolean {
if (allowedMethods.includes('*')) return true;
const normalizedCandidate = candidateMethod.trim().toUpperCase() || 'GET';
return allowedMethods.includes(normalizedCandidate);
}
function matchesNetworkPathPattern(
allowedPaths: string[],
candidatePath: string,
): boolean {
const normalizedCandidate = normalizeNetworkPathPattern(candidatePath || '/');
return allowedPaths.some((pattern) =>
globPatternToRegExp(normalizeNetworkPathPattern(pattern)).test(
normalizedCandidate,
),
);
}
function matchesAgentPattern(
ruleAgent: string,
candidateAgent: string,
): boolean {
if (ruleAgent === '*') return true;
return ruleAgent === normalizeNetworkAgent(candidateAgent);
}
function parseUrlNetworkTarget(rawUrl: string): {
host: string;
port: number;
path: string;
} | null {
try {
const parsed = new URL(rawUrl);
const host = parsed.hostname.trim().toLowerCase();
if (!host) return null;
const pathValue = parsed.pathname || '/';
const explicitPort = parsed.port ? normalizeNetworkPort(parsed.port) : null;
return {
host,
port:
explicitPort && explicitPort !== '*'
? explicitPort
: defaultPortForProtocol(parsed.protocol),
path: pathValue || '/',
};
} catch {
return null;
}
}
function inferBashHttpMethod(command: string): string {
const explicit = command.match(/\b(?:-X|--request)\s+([A-Za-z]+)/i);
if (explicit?.[1]) return explicit[1].toUpperCase();
if (/\b(?:--data(?:-raw|-binary)?|-d|--form|-F)\b/i.test(command)) {
return 'POST';
}
if (/\bwget\b/i.test(command)) return 'GET';
return 'GET';
}
function extractAbsolutePaths(input: string): string[] {
const paths = new Set<string>();
for (const match of input.matchAll(ABS_PATH_RE)) {
const candidate = String(match[2] || '').trim();
if (!candidate || candidate === '/' || candidate === '//') continue;
try {
paths.add(fs.realpathSync(candidate));
} catch {
paths.add(path.resolve(candidate));
}
}
return [...paths];
}
function stripHereDocBodies(command: string): string {
const lines = command.split(/\r?\n/);
const kept: string[] = [];
let delimiter: string | null = null;
for (const line of lines) {
if (delimiter) {
if (line.trim() === delimiter) {
delimiter = null;
}
continue;
}
kept.push(line);
const match = line.match(
/<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))/,
);
delimiter = match?.[1] || match?.[2] || match?.[3] || null;
}
return kept.join('\n');
}
function tokenizeShellSegment(segment: string): string[] {
const tokens: string[] = [];
let current = '';
let quote: "'" | '"' | null = null;
for (let index = 0; index < segment.length; index += 1) {
const char = segment[index];
if (quote) {
if (char === quote) {
quote = null;
continue;
}
if (char === '\\' && quote === '"' && index + 1 < segment.length) {
current += segment[index + 1];
index += 1;
continue;
}
current += char;
continue;
}
if (char === "'" || char === '"') {
quote = char;
continue;
}
if (/\s/.test(char)) {
if (current) {
tokens.push(current);
current = '';
}
continue;
}
current += char;
}
if (current) tokens.push(current);
return tokens;
}
function sanitizeInterpreterInlineScripts(segment: string): string {
const tokens = tokenizeShellSegment(segment);
if (tokens.length === 0) return segment.trim();
const executable = path.posix.basename(tokens[0].trim().toLowerCase());
let inlineFlags: Set<string> | null = null;
if (executable === 'node' || executable === 'nodejs') {
inlineFlags = new Set(['-e', '--eval', '-p', '--print']);
} else if (/^python(?:\d+(?:\.\d+)*)?$/.test(executable)) {
inlineFlags = new Set(['-c']);
} else if (executable === 'perl' || executable === 'ruby') {
inlineFlags = new Set(['-e']);
} else if (executable === 'php') {
inlineFlags = new Set(['-r']);
}
if (!inlineFlags) return segment.trim();
const sanitized: string[] = [];
for (let index = 0; index < tokens.length; index += 1) {
const token = tokens[index];
const normalized = token.trim().toLowerCase();
sanitized.push(token);
if (!inlineFlags.has(normalized)) continue;
if (index + 1 >= tokens.length) continue;
sanitized.push('__INLINE_SCRIPT__');
index += 1;
}
return sanitized.join(' ');
}
function buildBashInspectionSurface(command: string): string {
const stripped = stripHereDocBodies(command);
return splitCommandSegments(stripped)
.map((segment) => sanitizeInterpreterInlineScripts(segment))
.join(' ; ');
}
function splitCommandSegments(command: string): string[] {
const segments: string[] = [];
let current = '';
let quote: "'" | '"' | null = null;
for (let index = 0; index < command.length; index += 1) {
const char = command[index];
const next = command[index + 1];
if (char === "'" && quote !== '"') {
quote = quote === "'" ? null : "'";
current += char;
continue;
}
if (char === '"' && quote !== "'") {
quote = quote === '"' ? null : '"';
current += char;
continue;
}
if (!quote) {
if (char === ';') {
if (current.trim()) segments.push(current.trim());
current = '';
continue;
}
if ((char === '&' || char === '|') && next === char) {
if (current.trim()) segments.push(current.trim());
current = '';
index += 1;
continue;
}
if (char === '|') {
if (current.trim()) segments.push(current.trim());
current = '';
continue;
}
}
current += char;
}
if (current.trim()) segments.push(current.trim());
return segments;
}
function unquotePathToken(rawValue: string): string {
const trimmed = rawValue.trim();
if (
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
) {
return trimmed.slice(1, -1);
}
return trimmed;
}
function pushAbsolutePath(
output: Set<string>,
rawValue: string | undefined,
): void {
const candidate = unquotePathToken(String(rawValue || ''));
if (!candidate.startsWith('/')) return;
output.add(candidate);
}
function extractLikelyWritePaths(command: string): string[] {
const paths = new Set<string>();
const segments = splitCommandSegments(command);
for (const segment of segments) {
const segmentAbsPaths = extractAbsolutePaths(segment);
for (const match of segment.matchAll(
/(?:^|\s)(?:--out|-o)\s+("[^"]+"|'[^']+'|\/[^\s"'`;,|&()<>]+)/g,
)) {
pushAbsolutePath(paths, match[1]);
}
for (const match of segment.matchAll(
/(?:^|[^>])>>?\s*("[^"]+"|'[^']+'|\/[^\s"'`;,|&()<>]+)/g,
)) {
pushAbsolutePath(paths, match[1]);
}
for (const match of segment.matchAll(
/(?:^|\s)tee(?:\s+-a)?\s+("[^"]+"|'[^']+'|\/[^\s"'`;,|&()<>]+)/g,
)) {
pushAbsolutePath(paths, match[1]);
}
if (/^\s*(mkdir|touch|chmod|chown)\b/i.test(segment)) {
for (const candidate of segmentAbsPaths) {
paths.add(candidate);
}
}
if (/^\s*(cp|mv)\b/i.test(segment)) {
const destination = segmentAbsPaths.at(-1);
if (destination) paths.add(destination);
}
}
return [...paths];
}
function isWithinResolvedRoot(candidate: string, root: string): boolean {
const resolvedCandidate = path.resolve(candidate);
const resolvedRoot = path.resolve(root);
return (
resolvedCandidate === resolvedRoot ||
resolvedCandidate.startsWith(`${resolvedRoot}${path.sep}`)
);
}
function isWorkspacePath(rawPath: string): boolean {
return (
isWithinResolvedRoot(rawPath, WORKSPACE_ROOT_DISPLAY) ||
isWithinResolvedRoot(rawPath, WORKSPACE_ROOT_ACTUAL)
);
}
function isScratchPath(rawPath: string): boolean {
return SCRATCH_ROOTS.some((root) => isWithinResolvedRoot(rawPath, root));
}
function primaryPathKey(rawPath: string): string {
const normalized = normalizePathValue(rawPath);
if (!normalized) return 'root';
const [first] = normalized.split('/');
return first || 'root';
}
function parseModeFromApproveMatch(
match: RegExpMatchArray | null,
): ApprovalMode {
const scope = String(match?.[2] || '').toLowerCase();
if (scope.includes('all')) return 'all';
if (scope.includes('agent')) return 'agent';
if (scope.includes('session')) return 'session';
return 'once';
}
function parseApprovalDirective(input: string): {
kind: 'approve' | 'deny';
mode?: ApprovalMode;
requestId: string;
} | null {
const normalized = input.trim();
if (!normalized) return null;
const directiveCandidates = [
normalized,
normalized.replace(/^(?:<@!?\d+>\s*)+/, ''),
];
for (const candidate of directiveCandidates) {
if (!candidate) continue;
const approveMatch = candidate.match(APPROVE_RE);
if (approveMatch) {
return {
kind: 'approve',
mode: parseModeFromApproveMatch(approveMatch),
requestId: String(approveMatch[1] || '').trim(),
};
}
const denyMatch = candidate.match(DENY_RE);
if (denyMatch) {
return {
kind: 'deny',
requestId: String(denyMatch[1] || '').trim(),
};
}
}
return null;
}
function parseApprovalUserResponse(input: string): {
kind: 'approve' | 'deny';
mode?: ApprovalMode;
requestId: string;
} | null {
const normalized = input.trim();
if (!normalized) return null;
const candidates: string[] = [];
const pushCandidate = (value: string): void => {
const trimmed = value.trim();
if (!trimmed) return;
if (candidates.includes(trimmed)) return;
candidates.push(trimmed);
};
pushCandidate(normalized);
pushCandidate(normalized.replace(/^(?:<@!?\d+>\s*)+/, ''));
const batchTailMatch = normalized.match(/Message\s+\d+\s*:\s*([\s\S]+)$/i);
if (batchTailMatch?.[1]) {
pushCandidate(batchTailMatch[1]);
}
const lines = normalized
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
if (lines.length > 0) {
pushCandidate(lines[lines.length - 1]);
}
for (const candidate of candidates) {
const parsed = parseApprovalDirective(candidate);
if (parsed) return parsed;
}
return null;
}
interface PersistedApprovalTrustStore {
version: 2;
allowlistedActions: string[];
allowlistedFingerprints: string[];
updatedAt: string;
}
function parsePersistedTrustStore(
raw: string,
): PersistedApprovalTrustStore | null {
try {
const parsed = JSON.parse(raw) as unknown;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
return null;
const record = parsed as Record<string, unknown>;
const allowlistedActions = Array.isArray(record.allowlistedActions)
? record.allowlistedActions
.map((value) => String(value || '').trim())
.filter(Boolean)
: Array.isArray(record.trustedActions)
? record.trustedActions
.map((value) => String(value || '').trim())
.filter(Boolean)
: [];
const allowlistedFingerprints = Array.isArray(
record.allowlistedFingerprints,
)
? record.allowlistedFingerprints
.map((value) => String(value || '').trim())
.filter(Boolean)
: Array.isArray(record.trustedFingerprints)
? record.trustedFingerprints
.map((value) => String(value || '').trim())
.filter(Boolean)
: [];
return {
version: 2,
allowlistedActions,
allowlistedFingerprints,
updatedAt:
typeof record.updatedAt === 'string'
? record.updatedAt
: new Date().toISOString(),
};
} catch {
return null;
}
}
export class TrustedCoworkerApprovalRuntime {
private readonly policyPath: string;
private readonly agentTrustStorePath: string;
private readonly legacyAgentTrustStorePath: string;
private readonly trustStorePath: string;
private loadedPolicy: ApprovalPolicyConfig = DEFAULT_POLICY;
private policyMtimeMs = -1;
private readonly pending = new Map<string, PendingApproval>();
private readonly actionExecutionCounts = new Map<string, number>();
private readonly explicitApprovalCounts = new Map<string, number>();
private readonly oneShotFingerprints = new Set<string>();
private readonly sessionTrustedActions = new Set<string>();
private readonly agentTrustedActions = new Set<string>();
private readonly agentTrustedFingerprints = new Set<string>();
private readonly allowlistedActions = new Set<string>();
private readonly allowlistedFingerprints = new Set<string>();
private readonly seenNetworkHosts = new Set<string>();
private fullAutoEnabled = false;
private readonly fullAutoNeverApprove = new Set<string>();
constructor(
policyPath = POLICY_PATH,
agentTrustStorePath = AGENT_TRUST_STORE_PATH,