@sanctuary-framework/mcp-server 0.5.14 → 0.5.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +2685 -153
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2683 -151
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +2683 -151
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +440 -13
- package/dist/index.d.ts +440 -13
- package/dist/index.js +2680 -150
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -15,6 +15,9 @@ import { createServer as createServer$2 } from 'http';
|
|
|
15
15
|
import { createServer as createServer$1 } from 'https';
|
|
16
16
|
import { readFileSync, statSync } from 'fs';
|
|
17
17
|
import { exec, execSync } from 'child_process';
|
|
18
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
19
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
20
|
+
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
|
|
18
21
|
|
|
19
22
|
var __defProp = Object.defineProperty;
|
|
20
23
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
@@ -3816,8 +3819,10 @@ var DEFAULT_POLICY = {
|
|
|
3816
3819
|
"decommission_certificate",
|
|
3817
3820
|
"reputation_publish",
|
|
3818
3821
|
// SEC-039: Explicit Tier 1 — sends data to external API
|
|
3819
|
-
"sovereignty_profile_update"
|
|
3822
|
+
"sovereignty_profile_update",
|
|
3820
3823
|
// Changes enforcement behavior — always requires approval
|
|
3824
|
+
"governor_reset"
|
|
3825
|
+
// Clears all runtime governance state — always requires approval
|
|
3821
3826
|
],
|
|
3822
3827
|
tier2_anomaly: DEFAULT_TIER2,
|
|
3823
3828
|
tier3_always_allow: [
|
|
@@ -3873,11 +3878,16 @@ var DEFAULT_POLICY = {
|
|
|
3873
3878
|
"dashboard_open",
|
|
3874
3879
|
// SEC-039: Explicit Tier 3 — only generates a URL
|
|
3875
3880
|
"sovereignty_profile_get",
|
|
3876
|
-
"sovereignty_profile_generate_prompt"
|
|
3881
|
+
"sovereignty_profile_generate_prompt",
|
|
3882
|
+
// Agent needs its own config to generate system prompt
|
|
3883
|
+
"governor_status"
|
|
3877
3884
|
],
|
|
3878
3885
|
approval_channel: DEFAULT_CHANNEL
|
|
3879
3886
|
};
|
|
3880
3887
|
function extractOperationName(toolName) {
|
|
3888
|
+
if (toolName.startsWith("proxy/")) {
|
|
3889
|
+
return toolName;
|
|
3890
|
+
}
|
|
3881
3891
|
return toolName.startsWith("sanctuary/") ? toolName.slice("sanctuary/".length) : toolName;
|
|
3882
3892
|
}
|
|
3883
3893
|
function parsePolicy(content) {
|
|
@@ -3983,6 +3993,7 @@ tier1_always_approve:
|
|
|
3983
3993
|
- bootstrap_provide_guarantee
|
|
3984
3994
|
- reputation_publish
|
|
3985
3995
|
- sovereignty_profile_update
|
|
3996
|
+
- governor_reset
|
|
3986
3997
|
|
|
3987
3998
|
# \u2500\u2500\u2500 Tier 2: Behavioral Anomaly Detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
3988
3999
|
# Triggers approval when agent behavior deviates from its baseline.
|
|
@@ -4047,7 +4058,7 @@ tier3_always_allow:
|
|
|
4047
4058
|
- bridge_attest
|
|
4048
4059
|
- dashboard_open
|
|
4049
4060
|
- sovereignty_profile_get
|
|
4050
|
-
-
|
|
4061
|
+
- governor_status
|
|
4051
4062
|
|
|
4052
4063
|
# \u2500\u2500\u2500 Approval Channel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
4053
4064
|
# How Sanctuary reaches you when approval is needed.
|
|
@@ -5359,6 +5370,17 @@ function generateDashboardHTML(options) {
|
|
|
5359
5370
|
display: flex;
|
|
5360
5371
|
flex-direction: column;
|
|
5361
5372
|
gap: 8px;
|
|
5373
|
+
transition: border-color 0.2s;
|
|
5374
|
+
}
|
|
5375
|
+
|
|
5376
|
+
.profile-card.active {
|
|
5377
|
+
border-color: var(--green);
|
|
5378
|
+
}
|
|
5379
|
+
|
|
5380
|
+
.profile-card-header {
|
|
5381
|
+
display: flex;
|
|
5382
|
+
justify-content: space-between;
|
|
5383
|
+
align-items: center;
|
|
5362
5384
|
}
|
|
5363
5385
|
|
|
5364
5386
|
.profile-card-name {
|
|
@@ -5373,6 +5395,53 @@ function generateDashboardHTML(options) {
|
|
|
5373
5395
|
line-height: 1.4;
|
|
5374
5396
|
}
|
|
5375
5397
|
|
|
5398
|
+
/* Toggle switch */
|
|
5399
|
+
.toggle-switch {
|
|
5400
|
+
position: relative;
|
|
5401
|
+
width: 36px;
|
|
5402
|
+
height: 20px;
|
|
5403
|
+
flex-shrink: 0;
|
|
5404
|
+
}
|
|
5405
|
+
|
|
5406
|
+
.toggle-switch input {
|
|
5407
|
+
opacity: 0;
|
|
5408
|
+
width: 0;
|
|
5409
|
+
height: 0;
|
|
5410
|
+
}
|
|
5411
|
+
|
|
5412
|
+
.toggle-slider {
|
|
5413
|
+
position: absolute;
|
|
5414
|
+
cursor: pointer;
|
|
5415
|
+
top: 0;
|
|
5416
|
+
left: 0;
|
|
5417
|
+
right: 0;
|
|
5418
|
+
bottom: 0;
|
|
5419
|
+
background-color: var(--border);
|
|
5420
|
+
border-radius: 10px;
|
|
5421
|
+
transition: background-color 0.2s;
|
|
5422
|
+
}
|
|
5423
|
+
|
|
5424
|
+
.toggle-slider::before {
|
|
5425
|
+
content: "";
|
|
5426
|
+
position: absolute;
|
|
5427
|
+
height: 14px;
|
|
5428
|
+
width: 14px;
|
|
5429
|
+
left: 3px;
|
|
5430
|
+
bottom: 3px;
|
|
5431
|
+
background-color: var(--text-secondary);
|
|
5432
|
+
border-radius: 50%;
|
|
5433
|
+
transition: transform 0.2s, background-color 0.2s;
|
|
5434
|
+
}
|
|
5435
|
+
|
|
5436
|
+
.toggle-switch input:checked + .toggle-slider {
|
|
5437
|
+
background-color: rgba(63, 185, 80, 0.3);
|
|
5438
|
+
}
|
|
5439
|
+
|
|
5440
|
+
.toggle-switch input:checked + .toggle-slider::before {
|
|
5441
|
+
transform: translateX(16px);
|
|
5442
|
+
background-color: var(--green);
|
|
5443
|
+
}
|
|
5444
|
+
|
|
5376
5445
|
.profile-badge {
|
|
5377
5446
|
display: inline-flex;
|
|
5378
5447
|
align-items: center;
|
|
@@ -5394,22 +5463,159 @@ function generateDashboardHTML(options) {
|
|
|
5394
5463
|
color: var(--text-secondary);
|
|
5395
5464
|
}
|
|
5396
5465
|
|
|
5466
|
+
.profile-card-actions {
|
|
5467
|
+
display: flex;
|
|
5468
|
+
gap: 6px;
|
|
5469
|
+
margin-top: 4px;
|
|
5470
|
+
}
|
|
5471
|
+
|
|
5472
|
+
.config-btn {
|
|
5473
|
+
padding: 3px 8px;
|
|
5474
|
+
border: 1px solid var(--border);
|
|
5475
|
+
border-radius: 4px;
|
|
5476
|
+
background-color: transparent;
|
|
5477
|
+
color: var(--text-secondary);
|
|
5478
|
+
font-size: 10px;
|
|
5479
|
+
cursor: pointer;
|
|
5480
|
+
transition: color 0.2s, border-color 0.2s;
|
|
5481
|
+
}
|
|
5482
|
+
|
|
5483
|
+
.config-btn:hover {
|
|
5484
|
+
color: var(--blue);
|
|
5485
|
+
border-color: var(--blue);
|
|
5486
|
+
}
|
|
5487
|
+
|
|
5488
|
+
/* Configuration panels */
|
|
5489
|
+
.config-panel {
|
|
5490
|
+
display: none;
|
|
5491
|
+
margin-top: 8px;
|
|
5492
|
+
padding: 10px;
|
|
5493
|
+
background-color: var(--surface);
|
|
5494
|
+
border: 1px solid var(--border);
|
|
5495
|
+
border-radius: 4px;
|
|
5496
|
+
font-size: 11px;
|
|
5497
|
+
}
|
|
5498
|
+
|
|
5499
|
+
.config-panel.open {
|
|
5500
|
+
display: block;
|
|
5501
|
+
}
|
|
5502
|
+
|
|
5503
|
+
.config-panel-title {
|
|
5504
|
+
font-size: 11px;
|
|
5505
|
+
font-weight: 600;
|
|
5506
|
+
color: var(--text-primary);
|
|
5507
|
+
margin-bottom: 8px;
|
|
5508
|
+
}
|
|
5509
|
+
|
|
5510
|
+
.config-row {
|
|
5511
|
+
display: flex;
|
|
5512
|
+
align-items: center;
|
|
5513
|
+
gap: 8px;
|
|
5514
|
+
margin-bottom: 6px;
|
|
5515
|
+
}
|
|
5516
|
+
|
|
5517
|
+
.config-label {
|
|
5518
|
+
font-size: 11px;
|
|
5519
|
+
color: var(--text-secondary);
|
|
5520
|
+
min-width: 80px;
|
|
5521
|
+
}
|
|
5522
|
+
|
|
5523
|
+
.config-select, .config-input {
|
|
5524
|
+
background-color: var(--bg);
|
|
5525
|
+
border: 1px solid var(--border);
|
|
5526
|
+
border-radius: 4px;
|
|
5527
|
+
color: var(--text-primary);
|
|
5528
|
+
font-size: 11px;
|
|
5529
|
+
padding: 4px 8px;
|
|
5530
|
+
}
|
|
5531
|
+
|
|
5532
|
+
.config-info {
|
|
5533
|
+
font-size: 11px;
|
|
5534
|
+
color: var(--text-secondary);
|
|
5535
|
+
line-height: 1.5;
|
|
5536
|
+
}
|
|
5537
|
+
|
|
5538
|
+
.sensitivity-slider {
|
|
5539
|
+
display: flex;
|
|
5540
|
+
gap: 4px;
|
|
5541
|
+
}
|
|
5542
|
+
|
|
5543
|
+
.sensitivity-option {
|
|
5544
|
+
padding: 3px 10px;
|
|
5545
|
+
border: 1px solid var(--border);
|
|
5546
|
+
border-radius: 4px;
|
|
5547
|
+
background-color: transparent;
|
|
5548
|
+
color: var(--text-secondary);
|
|
5549
|
+
font-size: 10px;
|
|
5550
|
+
cursor: pointer;
|
|
5551
|
+
transition: all 0.2s;
|
|
5552
|
+
}
|
|
5553
|
+
|
|
5554
|
+
.sensitivity-option.selected {
|
|
5555
|
+
background-color: rgba(88, 166, 255, 0.15);
|
|
5556
|
+
color: var(--blue);
|
|
5557
|
+
border-color: var(--blue);
|
|
5558
|
+
}
|
|
5559
|
+
|
|
5560
|
+
.sensitivity-option:hover:not(.selected) {
|
|
5561
|
+
border-color: var(--text-secondary);
|
|
5562
|
+
}
|
|
5563
|
+
|
|
5564
|
+
/* Prompt section */
|
|
5397
5565
|
.prompt-section {
|
|
5398
|
-
margin-top:
|
|
5566
|
+
margin-top: 16px;
|
|
5399
5567
|
}
|
|
5400
5568
|
|
|
5401
|
-
.prompt-
|
|
5402
|
-
|
|
5403
|
-
min-height: 120px;
|
|
5569
|
+
.prompt-display {
|
|
5570
|
+
position: relative;
|
|
5404
5571
|
background-color: var(--bg);
|
|
5405
5572
|
border: 1px solid var(--border);
|
|
5406
5573
|
border-radius: 6px;
|
|
5574
|
+
margin-top: 8px;
|
|
5575
|
+
display: none;
|
|
5576
|
+
}
|
|
5577
|
+
|
|
5578
|
+
.prompt-display.visible {
|
|
5579
|
+
display: block;
|
|
5580
|
+
}
|
|
5581
|
+
|
|
5582
|
+
.prompt-display-header {
|
|
5583
|
+
display: flex;
|
|
5584
|
+
justify-content: space-between;
|
|
5585
|
+
align-items: center;
|
|
5586
|
+
padding: 8px 12px;
|
|
5587
|
+
border-bottom: 1px solid var(--border);
|
|
5588
|
+
}
|
|
5589
|
+
|
|
5590
|
+
.prompt-token-count {
|
|
5591
|
+
font-size: 11px;
|
|
5592
|
+
color: var(--text-secondary);
|
|
5593
|
+
}
|
|
5594
|
+
|
|
5595
|
+
.prompt-copy-btn {
|
|
5596
|
+
padding: 4px 10px;
|
|
5597
|
+
border: 1px solid var(--border);
|
|
5598
|
+
border-radius: 4px;
|
|
5599
|
+
background-color: var(--surface);
|
|
5407
5600
|
color: var(--text-primary);
|
|
5601
|
+
font-size: 11px;
|
|
5602
|
+
cursor: pointer;
|
|
5603
|
+
transition: border-color 0.2s;
|
|
5604
|
+
}
|
|
5605
|
+
|
|
5606
|
+
.prompt-copy-btn:hover {
|
|
5607
|
+
border-color: var(--blue);
|
|
5608
|
+
}
|
|
5609
|
+
|
|
5610
|
+
.prompt-content {
|
|
5611
|
+
max-height: 300px;
|
|
5612
|
+
overflow-y: auto;
|
|
5613
|
+
padding: 12px;
|
|
5408
5614
|
font-family: 'JetBrains Mono', monospace;
|
|
5409
5615
|
font-size: 12px;
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5616
|
+
line-height: 1.6;
|
|
5617
|
+
white-space: pre-wrap;
|
|
5618
|
+
color: var(--text-primary);
|
|
5413
5619
|
}
|
|
5414
5620
|
|
|
5415
5621
|
.prompt-actions {
|
|
@@ -5796,37 +6002,173 @@ function generateDashboardHTML(options) {
|
|
|
5796
6002
|
</div>
|
|
5797
6003
|
<div class="profile-cards" id="profile-cards">
|
|
5798
6004
|
<div class="profile-card" data-feature="audit_logging">
|
|
5799
|
-
<div class="profile-card-
|
|
6005
|
+
<div class="profile-card-header">
|
|
6006
|
+
<div class="profile-card-name">Audit Logging</div>
|
|
6007
|
+
<label class="toggle-switch">
|
|
6008
|
+
<input type="checkbox" id="toggle-audit_logging" data-feature="audit_logging">
|
|
6009
|
+
<span class="toggle-slider"></span>
|
|
6010
|
+
</label>
|
|
6011
|
+
</div>
|
|
5800
6012
|
<div class="profile-badge disabled" id="badge-audit_logging">OFF</div>
|
|
5801
6013
|
<div class="profile-card-desc">Encrypted audit trail of all tool calls</div>
|
|
6014
|
+
<div class="profile-card-actions">
|
|
6015
|
+
<button class="config-btn" data-config="audit_logging">Configure</button>
|
|
6016
|
+
</div>
|
|
6017
|
+
<div class="config-panel" id="config-audit_logging">
|
|
6018
|
+
<div class="config-info">Audit logging is always-on when enabled. All tool calls, gate decisions, and profile changes are recorded to an encrypted audit trail. No additional configuration needed.</div>
|
|
6019
|
+
</div>
|
|
5802
6020
|
</div>
|
|
5803
6021
|
<div class="profile-card" data-feature="injection_detection">
|
|
5804
|
-
<div class="profile-card-
|
|
6022
|
+
<div class="profile-card-header">
|
|
6023
|
+
<div class="profile-card-name">Injection Detection</div>
|
|
6024
|
+
<label class="toggle-switch">
|
|
6025
|
+
<input type="checkbox" id="toggle-injection_detection" data-feature="injection_detection">
|
|
6026
|
+
<span class="toggle-slider"></span>
|
|
6027
|
+
</label>
|
|
6028
|
+
</div>
|
|
5805
6029
|
<div class="profile-badge disabled" id="badge-injection_detection">OFF</div>
|
|
5806
6030
|
<div class="profile-card-desc">Scans tool arguments for prompt injection</div>
|
|
6031
|
+
<div class="profile-card-actions">
|
|
6032
|
+
<button class="config-btn" data-config="injection_detection">Configure</button>
|
|
6033
|
+
</div>
|
|
6034
|
+
<div class="config-panel" id="config-injection_detection">
|
|
6035
|
+
<div class="config-panel-title">Sensitivity</div>
|
|
6036
|
+
<div class="sensitivity-slider">
|
|
6037
|
+
<button class="sensitivity-option" data-sensitivity="low">Low</button>
|
|
6038
|
+
<button class="sensitivity-option selected" data-sensitivity="medium">Medium</button>
|
|
6039
|
+
<button class="sensitivity-option" data-sensitivity="high">High</button>
|
|
6040
|
+
</div>
|
|
6041
|
+
</div>
|
|
5807
6042
|
</div>
|
|
5808
6043
|
<div class="profile-card" data-feature="context_gating">
|
|
5809
|
-
<div class="profile-card-
|
|
6044
|
+
<div class="profile-card-header">
|
|
6045
|
+
<div class="profile-card-name">Context Gating</div>
|
|
6046
|
+
<label class="toggle-switch">
|
|
6047
|
+
<input type="checkbox" id="toggle-context_gating" data-feature="context_gating">
|
|
6048
|
+
<span class="toggle-slider"></span>
|
|
6049
|
+
</label>
|
|
6050
|
+
</div>
|
|
5810
6051
|
<div class="profile-badge disabled" id="badge-context_gating">OFF</div>
|
|
5811
6052
|
<div class="profile-card-desc">Controls context flow to remote providers</div>
|
|
6053
|
+
<div class="profile-card-actions">
|
|
6054
|
+
<button class="config-btn" data-config="context_gating">Configure</button>
|
|
6055
|
+
</div>
|
|
6056
|
+
<div class="config-panel" id="config-context_gating">
|
|
6057
|
+
<div class="config-panel-title">Active Policy</div>
|
|
6058
|
+
<div class="config-row">
|
|
6059
|
+
<span class="config-label">Policy ID:</span>
|
|
6060
|
+
<select class="config-select" id="config-context-policy">
|
|
6061
|
+
<option value="">None selected</option>
|
|
6062
|
+
</select>
|
|
6063
|
+
</div>
|
|
6064
|
+
<div class="config-info" style="margin-top: 6px;">Use MCP tool <code style="color: var(--blue);">sanctuary/context_gate_set_policy</code> or <code style="color: var(--blue);">sanctuary/context_gate_apply_template</code> to create policies.</div>
|
|
6065
|
+
</div>
|
|
5812
6066
|
</div>
|
|
5813
6067
|
<div class="profile-card" data-feature="approval_gate">
|
|
5814
|
-
<div class="profile-card-
|
|
6068
|
+
<div class="profile-card-header">
|
|
6069
|
+
<div class="profile-card-name">Approval Gates</div>
|
|
6070
|
+
<label class="toggle-switch">
|
|
6071
|
+
<input type="checkbox" id="toggle-approval_gate" data-feature="approval_gate">
|
|
6072
|
+
<span class="toggle-slider"></span>
|
|
6073
|
+
</label>
|
|
6074
|
+
</div>
|
|
5815
6075
|
<div class="profile-badge disabled" id="badge-approval_gate">OFF</div>
|
|
5816
6076
|
<div class="profile-card-desc">Human approval for high-risk operations</div>
|
|
6077
|
+
<div class="profile-card-actions">
|
|
6078
|
+
<button class="config-btn" data-config="approval_gate">Configure</button>
|
|
6079
|
+
</div>
|
|
6080
|
+
<div class="config-panel" id="config-approval_gate">
|
|
6081
|
+
<div class="config-panel-title">Tier Assignments</div>
|
|
6082
|
+
<div class="config-info">
|
|
6083
|
+
<strong style="color: var(--red);">Tier 1 (always approve):</strong> export, import, key rotation, deletion<br>
|
|
6084
|
+
<strong style="color: var(--amber);">Tier 2 (approve on anomaly):</strong> new namespaces, unfamiliar counterparties, frequency spikes<br>
|
|
6085
|
+
<strong style="color: var(--green);">Tier 3 (auto-allow):</strong> standard operations, queries, reads
|
|
6086
|
+
</div>
|
|
6087
|
+
</div>
|
|
5817
6088
|
</div>
|
|
5818
6089
|
<div class="profile-card" data-feature="zk_proofs">
|
|
5819
|
-
<div class="profile-card-
|
|
6090
|
+
<div class="profile-card-header">
|
|
6091
|
+
<div class="profile-card-name">ZK Proofs</div>
|
|
6092
|
+
<label class="toggle-switch">
|
|
6093
|
+
<input type="checkbox" id="toggle-zk_proofs" data-feature="zk_proofs">
|
|
6094
|
+
<span class="toggle-slider"></span>
|
|
6095
|
+
</label>
|
|
6096
|
+
</div>
|
|
5820
6097
|
<div class="profile-badge disabled" id="badge-zk_proofs">OFF</div>
|
|
5821
6098
|
<div class="profile-card-desc">Prove claims without revealing data</div>
|
|
6099
|
+
<div class="profile-card-actions">
|
|
6100
|
+
<button class="config-btn" data-config="zk_proofs">Configure</button>
|
|
6101
|
+
</div>
|
|
6102
|
+
<div class="config-panel" id="config-zk_proofs">
|
|
6103
|
+
<div class="config-info">Zero-knowledge proofs use Pedersen commitments on Ristretto255 and Schnorr proofs. No additional configuration needed. Available tools: <code style="color: var(--blue);">sanctuary/zk_commit</code>, <code style="color: var(--blue);">sanctuary/zk_prove</code>, <code style="color: var(--blue);">sanctuary/zk_range_prove</code>.</div>
|
|
6104
|
+
</div>
|
|
5822
6105
|
</div>
|
|
5823
6106
|
</div>
|
|
5824
6107
|
<div class="prompt-section">
|
|
5825
6108
|
<div class="prompt-actions">
|
|
5826
6109
|
<button class="prompt-btn primary" id="generate-prompt-btn">Generate System Prompt</button>
|
|
5827
|
-
<button class="prompt-btn" id="copy-prompt-btn" style="display:none;">Copy</button>
|
|
5828
6110
|
</div>
|
|
5829
|
-
<
|
|
6111
|
+
<div class="prompt-display" id="prompt-display">
|
|
6112
|
+
<div class="prompt-display-header">
|
|
6113
|
+
<span class="prompt-token-count" id="prompt-token-count"></span>
|
|
6114
|
+
<button class="prompt-copy-btn" id="copy-prompt-btn">Copy to Clipboard</button>
|
|
6115
|
+
</div>
|
|
6116
|
+
<div class="prompt-content" id="system-prompt-output"></div>
|
|
6117
|
+
</div>
|
|
6118
|
+
</div>
|
|
6119
|
+
</div>
|
|
6120
|
+
|
|
6121
|
+
<!-- Upstream Servers Panel -->
|
|
6122
|
+
<div class="profile-panel" id="proxy-servers-panel">
|
|
6123
|
+
<div class="panel-header">
|
|
6124
|
+
<div class="panel-title">Upstream Servers</div>
|
|
6125
|
+
<button class="panel-action" id="add-proxy-server-btn">+ Add Server</button>
|
|
6126
|
+
</div>
|
|
6127
|
+
<div id="proxy-servers-list">
|
|
6128
|
+
<div class="empty-state">No upstream servers configured</div>
|
|
6129
|
+
</div>
|
|
6130
|
+
|
|
6131
|
+
<!-- Add Server Form (hidden by default) -->
|
|
6132
|
+
<div id="add-server-form" style="display: none; padding: 16px; border-top: 1px solid var(--border);">
|
|
6133
|
+
<div style="margin-bottom: 12px;">
|
|
6134
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Server Name</label>
|
|
6135
|
+
<input type="text" id="new-server-name" placeholder="e.g., filesystem" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
|
|
6136
|
+
</div>
|
|
6137
|
+
<div style="margin-bottom: 12px;">
|
|
6138
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Transport Type</label>
|
|
6139
|
+
<select id="new-server-transport" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
|
|
6140
|
+
<option value="stdio">stdio</option>
|
|
6141
|
+
<option value="sse">SSE</option>
|
|
6142
|
+
</select>
|
|
6143
|
+
</div>
|
|
6144
|
+
<div id="stdio-fields">
|
|
6145
|
+
<div style="margin-bottom: 12px;">
|
|
6146
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Command</label>
|
|
6147
|
+
<input type="text" id="new-server-command" placeholder="e.g., npx -y @modelcontextprotocol/server-filesystem" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
|
|
6148
|
+
</div>
|
|
6149
|
+
<div style="margin-bottom: 12px;">
|
|
6150
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Arguments (comma-separated)</label>
|
|
6151
|
+
<input type="text" id="new-server-args" placeholder="e.g., /Users/me/allowed-dir" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
|
|
6152
|
+
</div>
|
|
6153
|
+
</div>
|
|
6154
|
+
<div id="sse-fields" style="display: none;">
|
|
6155
|
+
<div style="margin-bottom: 12px;">
|
|
6156
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Server URL</label>
|
|
6157
|
+
<input type="text" id="new-server-url" placeholder="e.g., http://localhost:3001/sse" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
|
|
6158
|
+
</div>
|
|
6159
|
+
</div>
|
|
6160
|
+
<div style="margin-bottom: 12px;">
|
|
6161
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Default Tier</label>
|
|
6162
|
+
<select id="new-server-tier" style="width: 100%; padding: 8px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; color: var(--text-primary); font-size: 13px;">
|
|
6163
|
+
<option value="1">Tier 1 (Always approve)</option>
|
|
6164
|
+
<option value="2" selected>Tier 2 (Anomaly detection)</option>
|
|
6165
|
+
<option value="3">Tier 3 (Always allow)</option>
|
|
6166
|
+
</select>
|
|
6167
|
+
</div>
|
|
6168
|
+
<div style="display: flex; gap: 8px;">
|
|
6169
|
+
<button id="save-server-btn" style="flex: 1; padding: 8px; background: var(--green); color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px;">Save</button>
|
|
6170
|
+
<button id="cancel-server-btn" style="flex: 1; padding: 8px; background: var(--surface); color: var(--text-secondary); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px;">Cancel</button>
|
|
6171
|
+
</div>
|
|
5830
6172
|
</div>
|
|
5831
6173
|
</div>
|
|
5832
6174
|
|
|
@@ -6317,8 +6659,34 @@ function generateDashboardHTML(options) {
|
|
|
6317
6659
|
removePendingRequest(data.requestId);
|
|
6318
6660
|
});
|
|
6319
6661
|
|
|
6320
|
-
eventSource.addEventListener('sovereignty-profile-update', () => {
|
|
6321
|
-
|
|
6662
|
+
eventSource.addEventListener('sovereignty-profile-update', (e) => {
|
|
6663
|
+
try {
|
|
6664
|
+
const data = JSON.parse(e.data);
|
|
6665
|
+
if (data.profile) {
|
|
6666
|
+
applyProfileToUI(data.profile);
|
|
6667
|
+
}
|
|
6668
|
+
if (data.system_prompt) {
|
|
6669
|
+
apiState.systemPrompt = data.system_prompt;
|
|
6670
|
+
updatePromptDisplay(data.system_prompt);
|
|
6671
|
+
}
|
|
6672
|
+
} catch (err) {
|
|
6673
|
+
// Fallback to full refresh
|
|
6674
|
+
updateSovereigntyProfile();
|
|
6675
|
+
}
|
|
6676
|
+
});
|
|
6677
|
+
|
|
6678
|
+
eventSource.addEventListener('proxy-server-status', (e) => {
|
|
6679
|
+
try {
|
|
6680
|
+
const data = JSON.parse(e.data);
|
|
6681
|
+
updateProxyServerStatus(data.server, data.state, data.tool_count, data.error);
|
|
6682
|
+
} catch (err) {
|
|
6683
|
+
// Fallback to full refresh
|
|
6684
|
+
loadProxyServers();
|
|
6685
|
+
}
|
|
6686
|
+
});
|
|
6687
|
+
|
|
6688
|
+
eventSource.addEventListener('proxy-servers-update', () => {
|
|
6689
|
+
loadProxyServers();
|
|
6322
6690
|
});
|
|
6323
6691
|
|
|
6324
6692
|
eventSource.onerror = () => {
|
|
@@ -6336,7 +6704,7 @@ function generateDashboardHTML(options) {
|
|
|
6336
6704
|
|
|
6337
6705
|
const feed = document.getElementById('activity-feed');
|
|
6338
6706
|
const html = \`
|
|
6339
|
-
<div class="activity-item \${item.type}">
|
|
6707
|
+
<div class="activity-item \${esc(item.type)}">
|
|
6340
6708
|
<div class="activity-type">\${esc(item.title)}</div>
|
|
6341
6709
|
<div class="activity-content">\${esc(item.content)}</div>
|
|
6342
6710
|
<div class="activity-time">\${formatTime(item.timestamp)}</div>
|
|
@@ -6478,26 +6846,16 @@ function generateDashboardHTML(options) {
|
|
|
6478
6846
|
});
|
|
6479
6847
|
|
|
6480
6848
|
// Sovereignty Profile
|
|
6849
|
+
let profileToggleLock = false;
|
|
6850
|
+
|
|
6481
6851
|
async function updateSovereigntyProfile() {
|
|
6482
6852
|
try {
|
|
6483
6853
|
const data = await fetchAPI('/api/sovereignty-profile');
|
|
6484
6854
|
if (data && data.profile) {
|
|
6485
|
-
|
|
6486
|
-
for (const [key, value] of Object.entries(features)) {
|
|
6487
|
-
const badge = document.getElementById('badge-' + key);
|
|
6488
|
-
if (badge) {
|
|
6489
|
-
const enabled = value && value.enabled;
|
|
6490
|
-
badge.textContent = enabled ? 'ON' : 'OFF';
|
|
6491
|
-
badge.className = 'profile-badge ' + (enabled ? 'enabled' : 'disabled');
|
|
6492
|
-
}
|
|
6493
|
-
}
|
|
6494
|
-
const updatedEl = document.getElementById('profile-updated-at');
|
|
6495
|
-
if (updatedEl && data.profile.updated_at) {
|
|
6496
|
-
updatedEl.textContent = 'Updated: ' + new Date(data.profile.updated_at).toLocaleString();
|
|
6497
|
-
}
|
|
6498
|
-
// Cache the prompt
|
|
6855
|
+
applyProfileToUI(data.profile);
|
|
6499
6856
|
if (data.system_prompt) {
|
|
6500
6857
|
apiState.systemPrompt = data.system_prompt;
|
|
6858
|
+
updatePromptDisplay(data.system_prompt);
|
|
6501
6859
|
}
|
|
6502
6860
|
}
|
|
6503
6861
|
} catch (e) {
|
|
@@ -6505,94 +6863,518 @@ function generateDashboardHTML(options) {
|
|
|
6505
6863
|
}
|
|
6506
6864
|
}
|
|
6507
6865
|
|
|
6508
|
-
|
|
6509
|
-
const
|
|
6510
|
-
|
|
6511
|
-
const
|
|
6512
|
-
const copyBtn = document.getElementById('copy-prompt-btn');
|
|
6513
|
-
textarea.value = data.system_prompt;
|
|
6514
|
-
textarea.style.display = 'block';
|
|
6515
|
-
copyBtn.style.display = 'inline-flex';
|
|
6516
|
-
}
|
|
6517
|
-
});
|
|
6866
|
+
function applyProfileToUI(profile) {
|
|
6867
|
+
const features = profile.features;
|
|
6868
|
+
for (const [key, value] of Object.entries(features)) {
|
|
6869
|
+
const enabled = value && value.enabled;
|
|
6518
6870
|
|
|
6519
|
-
|
|
6520
|
-
|
|
6521
|
-
|
|
6522
|
-
|
|
6523
|
-
|
|
6524
|
-
|
|
6525
|
-
btn.textContent = 'Copied!';
|
|
6526
|
-
setTimeout(() => { btn.textContent = original; }, 2000);
|
|
6527
|
-
} catch (err) {
|
|
6528
|
-
console.error('Copy failed:', err);
|
|
6529
|
-
}
|
|
6530
|
-
});
|
|
6871
|
+
// Update badge
|
|
6872
|
+
const badge = document.getElementById('badge-' + key);
|
|
6873
|
+
if (badge) {
|
|
6874
|
+
badge.textContent = enabled ? 'ON' : 'OFF';
|
|
6875
|
+
badge.className = 'profile-badge ' + (enabled ? 'enabled' : 'disabled');
|
|
6876
|
+
}
|
|
6531
6877
|
|
|
6532
|
-
|
|
6533
|
-
|
|
6534
|
-
|
|
6535
|
-
|
|
6536
|
-
|
|
6878
|
+
// Update toggle (without triggering change event)
|
|
6879
|
+
const toggle = document.getElementById('toggle-' + key);
|
|
6880
|
+
if (toggle && toggle.checked !== enabled) {
|
|
6881
|
+
profileToggleLock = true;
|
|
6882
|
+
toggle.checked = enabled;
|
|
6883
|
+
profileToggleLock = false;
|
|
6884
|
+
}
|
|
6885
|
+
|
|
6886
|
+
// Update card active state
|
|
6887
|
+
const card = document.querySelector('[data-feature="' + key + '"]');
|
|
6888
|
+
if (card) {
|
|
6889
|
+
card.classList.toggle('active', enabled);
|
|
6890
|
+
}
|
|
6891
|
+
|
|
6892
|
+
// Feature-specific config UI updates
|
|
6893
|
+
if (key === 'injection_detection' && value.sensitivity) {
|
|
6894
|
+
document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(btn) {
|
|
6895
|
+
btn.classList.toggle('selected', btn.getAttribute('data-sensitivity') === value.sensitivity);
|
|
6896
|
+
});
|
|
6897
|
+
}
|
|
6898
|
+
|
|
6899
|
+
if (key === 'context_gating' && value.policy_id) {
|
|
6900
|
+
const sel = document.getElementById('config-context-policy');
|
|
6901
|
+
if (sel) {
|
|
6902
|
+
// Add the policy as an option if not present
|
|
6903
|
+
let found = false;
|
|
6904
|
+
for (let i = 0; i < sel.options.length; i++) {
|
|
6905
|
+
if (sel.options[i].value === value.policy_id) { found = true; break; }
|
|
6906
|
+
}
|
|
6907
|
+
if (!found) {
|
|
6908
|
+
const opt = document.createElement('option');
|
|
6909
|
+
opt.value = value.policy_id;
|
|
6910
|
+
opt.textContent = value.policy_id;
|
|
6911
|
+
sel.appendChild(opt);
|
|
6912
|
+
}
|
|
6913
|
+
sel.value = value.policy_id;
|
|
6914
|
+
}
|
|
6915
|
+
}
|
|
6537
6916
|
}
|
|
6538
6917
|
|
|
6539
|
-
|
|
6540
|
-
|
|
6541
|
-
|
|
6542
|
-
|
|
6543
|
-
|
|
6544
|
-
updateSHR(),
|
|
6545
|
-
updateStatus(),
|
|
6546
|
-
updateSovereigntyProfile(),
|
|
6547
|
-
]);
|
|
6918
|
+
const updatedEl = document.getElementById('profile-updated-at');
|
|
6919
|
+
if (updatedEl && profile.updated_at) {
|
|
6920
|
+
updatedEl.textContent = 'Updated: ' + new Date(profile.updated_at).toLocaleString();
|
|
6921
|
+
}
|
|
6922
|
+
}
|
|
6548
6923
|
|
|
6549
|
-
|
|
6550
|
-
|
|
6924
|
+
function updatePromptDisplay(promptText) {
|
|
6925
|
+
const display = document.getElementById('prompt-display');
|
|
6926
|
+
const content = document.getElementById('system-prompt-output');
|
|
6927
|
+
const tokenCount = document.getElementById('prompt-token-count');
|
|
6928
|
+
if (!display || !content) return;
|
|
6551
6929
|
|
|
6552
|
-
|
|
6553
|
-
|
|
6930
|
+
if (promptText) {
|
|
6931
|
+
content.textContent = promptText;
|
|
6932
|
+
// Rough token estimate: word count * 1.3
|
|
6933
|
+
const words = promptText.split(/\\s+/).filter(function(w) { return w.length > 0; }).length;
|
|
6934
|
+
const tokens = Math.round(words * 1.3);
|
|
6935
|
+
tokenCount.textContent = '~' + tokens + ' tokens';
|
|
6936
|
+
display.classList.add('visible');
|
|
6937
|
+
}
|
|
6554
6938
|
}
|
|
6555
6939
|
|
|
6556
|
-
//
|
|
6557
|
-
|
|
6558
|
-
|
|
6559
|
-
|
|
6560
|
-
|
|
6561
|
-
}
|
|
6940
|
+
// Toggle handlers
|
|
6941
|
+
async function handleToggle(feature, enabled) {
|
|
6942
|
+
if (profileToggleLock) return;
|
|
6943
|
+
const payload = {};
|
|
6944
|
+
payload[feature] = { enabled: enabled };
|
|
6562
6945
|
|
|
6563
|
-
|
|
6564
|
-
|
|
6565
|
-
|
|
6566
|
-
|
|
6567
|
-
|
|
6568
|
-
|
|
6946
|
+
try {
|
|
6947
|
+
const response = await fetch(API_BASE + '/api/sovereignty-profile', {
|
|
6948
|
+
method: 'POST',
|
|
6949
|
+
headers: {
|
|
6950
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
6951
|
+
'Content-Type': 'application/json',
|
|
6952
|
+
},
|
|
6953
|
+
body: JSON.stringify(payload),
|
|
6954
|
+
});
|
|
6955
|
+
|
|
6956
|
+
if (response.status === 401) {
|
|
6957
|
+
redirectToLogin();
|
|
6958
|
+
return;
|
|
6959
|
+
}
|
|
6960
|
+
|
|
6961
|
+
if (response.ok) {
|
|
6962
|
+
const data = await response.json();
|
|
6963
|
+
if (data.profile) {
|
|
6964
|
+
applyProfileToUI(data.profile);
|
|
6965
|
+
}
|
|
6966
|
+
if (data.system_prompt) {
|
|
6967
|
+
apiState.systemPrompt = data.system_prompt;
|
|
6968
|
+
updatePromptDisplay(data.system_prompt);
|
|
6969
|
+
}
|
|
6970
|
+
} else {
|
|
6971
|
+
// Revert toggle on failure
|
|
6972
|
+
const toggle = document.getElementById('toggle-' + feature);
|
|
6973
|
+
if (toggle) {
|
|
6974
|
+
profileToggleLock = true;
|
|
6975
|
+
toggle.checked = !enabled;
|
|
6976
|
+
profileToggleLock = false;
|
|
6977
|
+
}
|
|
6978
|
+
}
|
|
6979
|
+
} catch (err) {
|
|
6980
|
+
console.error('Toggle update failed:', err);
|
|
6981
|
+
// Revert toggle
|
|
6982
|
+
const toggle = document.getElementById('toggle-' + feature);
|
|
6983
|
+
if (toggle) {
|
|
6984
|
+
profileToggleLock = true;
|
|
6985
|
+
toggle.checked = !enabled;
|
|
6986
|
+
profileToggleLock = false;
|
|
6987
|
+
}
|
|
6988
|
+
}
|
|
6989
|
+
}
|
|
6990
|
+
|
|
6991
|
+
// Wire up toggle switches
|
|
6992
|
+
document.querySelectorAll('.toggle-switch input').forEach(function(toggle) {
|
|
6993
|
+
toggle.addEventListener('change', function() {
|
|
6994
|
+
const feature = this.getAttribute('data-feature');
|
|
6995
|
+
handleToggle(feature, this.checked);
|
|
6996
|
+
});
|
|
6997
|
+
});
|
|
6998
|
+
|
|
6999
|
+
// Wire up configure buttons
|
|
7000
|
+
document.querySelectorAll('.config-btn').forEach(function(btn) {
|
|
7001
|
+
btn.addEventListener('click', function() {
|
|
7002
|
+
const feature = this.getAttribute('data-config');
|
|
7003
|
+
const panel = document.getElementById('config-' + feature);
|
|
7004
|
+
if (panel) {
|
|
7005
|
+
panel.classList.toggle('open');
|
|
7006
|
+
this.textContent = panel.classList.contains('open') ? 'Close' : 'Configure';
|
|
7007
|
+
}
|
|
7008
|
+
});
|
|
7009
|
+
});
|
|
7010
|
+
|
|
7011
|
+
// Injection sensitivity handler
|
|
7012
|
+
document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(btn) {
|
|
7013
|
+
btn.addEventListener('click', async function() {
|
|
7014
|
+
const sensitivity = this.getAttribute('data-sensitivity');
|
|
7015
|
+
const response = await fetch(API_BASE + '/api/sovereignty-profile', {
|
|
7016
|
+
method: 'POST',
|
|
7017
|
+
headers: {
|
|
7018
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
7019
|
+
'Content-Type': 'application/json',
|
|
7020
|
+
},
|
|
7021
|
+
body: JSON.stringify({ injection_detection: { sensitivity: sensitivity } }),
|
|
7022
|
+
});
|
|
7023
|
+
if (response.ok) {
|
|
7024
|
+
document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(b) {
|
|
7025
|
+
b.classList.toggle('selected', b.getAttribute('data-sensitivity') === sensitivity);
|
|
7026
|
+
});
|
|
7027
|
+
const data = await response.json();
|
|
7028
|
+
if (data.profile) applyProfileToUI(data.profile);
|
|
7029
|
+
if (data.system_prompt) {
|
|
7030
|
+
apiState.systemPrompt = data.system_prompt;
|
|
7031
|
+
updatePromptDisplay(data.system_prompt);
|
|
7032
|
+
}
|
|
7033
|
+
}
|
|
7034
|
+
});
|
|
7035
|
+
});
|
|
7036
|
+
|
|
7037
|
+
// Context gating policy selector handler
|
|
7038
|
+
document.getElementById('config-context-policy').addEventListener('change', async function() {
|
|
7039
|
+
const policyId = this.value;
|
|
7040
|
+
const response = await fetch(API_BASE + '/api/sovereignty-profile', {
|
|
7041
|
+
method: 'POST',
|
|
7042
|
+
headers: {
|
|
7043
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
7044
|
+
'Content-Type': 'application/json',
|
|
7045
|
+
},
|
|
7046
|
+
body: JSON.stringify({ context_gating: { policy_id: policyId } }),
|
|
7047
|
+
});
|
|
7048
|
+
if (response.ok) {
|
|
7049
|
+
const data = await response.json();
|
|
7050
|
+
if (data.profile) applyProfileToUI(data.profile);
|
|
7051
|
+
if (data.system_prompt) {
|
|
7052
|
+
apiState.systemPrompt = data.system_prompt;
|
|
7053
|
+
updatePromptDisplay(data.system_prompt);
|
|
7054
|
+
}
|
|
7055
|
+
}
|
|
7056
|
+
});
|
|
7057
|
+
|
|
7058
|
+
// Generate prompt button
|
|
7059
|
+
document.getElementById('generate-prompt-btn').addEventListener('click', async () => {
|
|
7060
|
+
const data = await fetchAPI('/api/sovereignty-profile');
|
|
7061
|
+
if (data && data.system_prompt) {
|
|
7062
|
+
apiState.systemPrompt = data.system_prompt;
|
|
7063
|
+
updatePromptDisplay(data.system_prompt);
|
|
7064
|
+
}
|
|
7065
|
+
});
|
|
7066
|
+
|
|
7067
|
+
// Copy prompt button
|
|
7068
|
+
document.getElementById('copy-prompt-btn').addEventListener('click', async () => {
|
|
7069
|
+
const content = document.getElementById('system-prompt-output');
|
|
7070
|
+
if (!content || !content.textContent) return;
|
|
7071
|
+
try {
|
|
7072
|
+
await navigator.clipboard.writeText(content.textContent);
|
|
7073
|
+
const btn = document.getElementById('copy-prompt-btn');
|
|
7074
|
+
const original = btn.textContent;
|
|
7075
|
+
btn.textContent = 'Copied!';
|
|
7076
|
+
setTimeout(() => { btn.textContent = original; }, 2000);
|
|
7077
|
+
} catch (err) {
|
|
7078
|
+
console.error('Copy failed:', err);
|
|
7079
|
+
}
|
|
7080
|
+
});
|
|
7081
|
+
|
|
7082
|
+
// \u2500\u2500 Proxy Server Management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
7083
|
+
|
|
7084
|
+
let proxyServers = [];
|
|
7085
|
+
|
|
7086
|
+
async function loadProxyServers() {
|
|
7087
|
+
try {
|
|
7088
|
+
const resp = await fetch(API_BASE + '/api/proxy/servers', {
|
|
7089
|
+
headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN },
|
|
7090
|
+
});
|
|
7091
|
+
if (!resp.ok) return;
|
|
7092
|
+
const data = await resp.json();
|
|
7093
|
+
proxyServers = data.servers || [];
|
|
7094
|
+
renderProxyServers();
|
|
7095
|
+
} catch (err) {
|
|
7096
|
+
// Proxy endpoint may not be available
|
|
7097
|
+
}
|
|
7098
|
+
}
|
|
7099
|
+
|
|
7100
|
+
function renderProxyServers() {
|
|
7101
|
+
const container = document.getElementById('proxy-servers-list');
|
|
7102
|
+
if (!container) return;
|
|
7103
|
+
|
|
7104
|
+
if (proxyServers.length === 0) {
|
|
7105
|
+
container.innerHTML = '<div class="empty-state">No upstream servers configured</div>';
|
|
7106
|
+
return;
|
|
7107
|
+
}
|
|
7108
|
+
|
|
7109
|
+
container.innerHTML = proxyServers.map(server => {
|
|
7110
|
+
const stateColor = server.state === 'connected' ? 'var(--green)' :
|
|
7111
|
+
server.state === 'connecting' ? 'var(--amber)' : 'var(--red)';
|
|
7112
|
+
const stateLabel = server.state || 'disconnected';
|
|
7113
|
+
const tierLabel = 'Tier ' + server.default_tier;
|
|
7114
|
+
|
|
7115
|
+
return \`
|
|
7116
|
+
<div class="proxy-server-card" data-server="\${esc(server.name)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border);">
|
|
7117
|
+
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
|
|
7118
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
7119
|
+
<span style="color: \${stateColor}; font-size: 10px;">\\u25CF</span>
|
|
7120
|
+
<span style="font-weight: 600; font-size: 14px;">\${esc(server.name)}</span>
|
|
7121
|
+
<span style="font-size: 11px; color: var(--text-secondary); background: var(--bg); padding: 2px 6px; border-radius: 3px;">\${esc(server.transport_type)}</span>
|
|
7122
|
+
</div>
|
|
7123
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
7124
|
+
<span style="font-size: 11px; color: var(--text-secondary);">\${server.tool_count} tools</span>
|
|
7125
|
+
<span style="font-size: 11px; color: var(--blue); background: rgba(88,166,255,0.1); padding: 2px 6px; border-radius: 3px;">\${tierLabel}</span>
|
|
7126
|
+
<button class="proxy-remove-btn" data-server="\${esc(server.name)}" style="background: none; border: none; color: var(--red); cursor: pointer; font-size: 14px; padding: 2px 6px;" title="Remove server">\\u00D7</button>
|
|
7127
|
+
</div>
|
|
7128
|
+
</div>
|
|
7129
|
+
<div style="font-size: 11px; color: var(--text-secondary);">
|
|
7130
|
+
Status: <span style="color: \${stateColor}">\${esc(stateLabel)}</span>
|
|
7131
|
+
\${server.error ? '<span style="color: var(--red);"> \u2014 ' + esc(server.error) + '</span>' : ''}
|
|
7132
|
+
</div>
|
|
7133
|
+
<div class="proxy-tools-expand" style="margin-top: 8px; display: none;">
|
|
7134
|
+
<div style="font-size: 11px; color: var(--text-secondary); margin-bottom: 4px;">Discovered Tools:</div>
|
|
7135
|
+
<div class="proxy-tools-list" style="font-size: 11px; font-family: monospace; color: var(--text-primary); max-height: 150px; overflow-y: auto;"></div>
|
|
7136
|
+
</div>
|
|
7137
|
+
</div>
|
|
7138
|
+
\`;
|
|
7139
|
+
}).join('');
|
|
7140
|
+
|
|
7141
|
+
// Attach remove handlers
|
|
7142
|
+
container.querySelectorAll('.proxy-remove-btn').forEach(btn => {
|
|
7143
|
+
btn.addEventListener('click', (e) => {
|
|
7144
|
+
const serverName = e.target.dataset.server;
|
|
7145
|
+
removeProxyServer(serverName);
|
|
7146
|
+
});
|
|
7147
|
+
});
|
|
7148
|
+
|
|
7149
|
+
// Attach expand/collapse on card click
|
|
7150
|
+
container.querySelectorAll('.proxy-server-card').forEach(card => {
|
|
7151
|
+
card.style.cursor = 'pointer';
|
|
7152
|
+
card.addEventListener('click', (e) => {
|
|
7153
|
+
if (e.target.classList.contains('proxy-remove-btn')) return;
|
|
7154
|
+
const expand = card.querySelector('.proxy-tools-expand');
|
|
7155
|
+
if (expand) {
|
|
7156
|
+
expand.style.display = expand.style.display === 'none' ? 'block' : 'none';
|
|
7157
|
+
}
|
|
7158
|
+
});
|
|
7159
|
+
});
|
|
7160
|
+
}
|
|
7161
|
+
|
|
7162
|
+
function updateProxyServerStatus(serverName, state, toolCount, error) {
|
|
7163
|
+
const server = proxyServers.find(s => s.name === serverName);
|
|
7164
|
+
if (server) {
|
|
7165
|
+
server.state = state;
|
|
7166
|
+
server.tool_count = toolCount;
|
|
7167
|
+
server.error = error;
|
|
7168
|
+
renderProxyServers();
|
|
7169
|
+
}
|
|
7170
|
+
}
|
|
7171
|
+
|
|
7172
|
+
async function addProxyServer(serverConfig) {
|
|
7173
|
+
const current = [...proxyServers];
|
|
7174
|
+
// Check for duplicate
|
|
7175
|
+
if (current.find(s => s.name === serverConfig.name)) {
|
|
7176
|
+
alert('A server with that name already exists');
|
|
7177
|
+
return;
|
|
7178
|
+
}
|
|
7179
|
+
current.push(serverConfig);
|
|
7180
|
+
|
|
7181
|
+
try {
|
|
7182
|
+
const resp = await fetch(API_BASE + '/api/proxy/servers', {
|
|
7183
|
+
method: 'POST',
|
|
7184
|
+
headers: {
|
|
7185
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
7186
|
+
'Content-Type': 'application/json',
|
|
7187
|
+
},
|
|
7188
|
+
body: JSON.stringify({ upstream_servers: current }),
|
|
7189
|
+
});
|
|
7190
|
+
if (!resp.ok) {
|
|
7191
|
+
const err = await resp.json();
|
|
7192
|
+
alert('Failed to add server: ' + (err.error || 'Unknown error'));
|
|
7193
|
+
return;
|
|
7194
|
+
}
|
|
7195
|
+
await loadProxyServers();
|
|
7196
|
+
} catch (err) {
|
|
7197
|
+
alert('Failed to add server: ' + err.message);
|
|
7198
|
+
}
|
|
7199
|
+
}
|
|
7200
|
+
|
|
7201
|
+
async function removeProxyServer(serverName) {
|
|
7202
|
+
if (!confirm('Remove upstream server "' + serverName + '"?')) return;
|
|
7203
|
+
|
|
7204
|
+
const updated = proxyServers.filter(s => s.name !== serverName);
|
|
7205
|
+
|
|
7206
|
+
try {
|
|
7207
|
+
const resp = await fetch(API_BASE + '/api/proxy/servers', {
|
|
7208
|
+
method: 'POST',
|
|
7209
|
+
headers: {
|
|
7210
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
7211
|
+
'Content-Type': 'application/json',
|
|
7212
|
+
},
|
|
7213
|
+
body: JSON.stringify({ upstream_servers: updated }),
|
|
7214
|
+
});
|
|
7215
|
+
if (!resp.ok) {
|
|
7216
|
+
const err = await resp.json();
|
|
7217
|
+
alert('Failed to remove server: ' + (err.error || 'Unknown error'));
|
|
7218
|
+
return;
|
|
7219
|
+
}
|
|
7220
|
+
await loadProxyServers();
|
|
7221
|
+
} catch (err) {
|
|
7222
|
+
alert('Failed to remove server: ' + err.message);
|
|
7223
|
+
}
|
|
7224
|
+
}
|
|
7225
|
+
|
|
7226
|
+
// Add Server form handlers
|
|
7227
|
+
(function setupProxyForm() {
|
|
7228
|
+
const addBtn = document.getElementById('add-proxy-server-btn');
|
|
7229
|
+
const form = document.getElementById('add-server-form');
|
|
7230
|
+
const saveBtn = document.getElementById('save-server-btn');
|
|
7231
|
+
const cancelBtn = document.getElementById('cancel-server-btn');
|
|
7232
|
+
const transportSelect = document.getElementById('new-server-transport');
|
|
7233
|
+
const stdioFields = document.getElementById('stdio-fields');
|
|
7234
|
+
const sseFields = document.getElementById('sse-fields');
|
|
7235
|
+
|
|
7236
|
+
if (!addBtn || !form) return;
|
|
7237
|
+
|
|
7238
|
+
addBtn.addEventListener('click', () => {
|
|
7239
|
+
form.style.display = form.style.display === 'none' ? 'block' : 'none';
|
|
7240
|
+
});
|
|
7241
|
+
|
|
7242
|
+
cancelBtn.addEventListener('click', () => {
|
|
7243
|
+
form.style.display = 'none';
|
|
7244
|
+
});
|
|
7245
|
+
|
|
7246
|
+
transportSelect.addEventListener('change', () => {
|
|
7247
|
+
if (transportSelect.value === 'stdio') {
|
|
7248
|
+
stdioFields.style.display = 'block';
|
|
7249
|
+
sseFields.style.display = 'none';
|
|
7250
|
+
} else {
|
|
7251
|
+
stdioFields.style.display = 'none';
|
|
7252
|
+
sseFields.style.display = 'block';
|
|
7253
|
+
}
|
|
7254
|
+
});
|
|
7255
|
+
|
|
7256
|
+
saveBtn.addEventListener('click', () => {
|
|
7257
|
+
const name = document.getElementById('new-server-name').value.trim();
|
|
7258
|
+
const type = transportSelect.value;
|
|
7259
|
+
const tier = parseInt(document.getElementById('new-server-tier').value, 10);
|
|
7260
|
+
|
|
7261
|
+
if (!name) { alert('Server name is required'); return; }
|
|
7262
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(name)) { alert('Name must contain only letters, numbers, hyphens, and underscores'); return; }
|
|
7263
|
+
|
|
7264
|
+
const transport = { type };
|
|
7265
|
+
if (type === 'stdio') {
|
|
7266
|
+
const command = document.getElementById('new-server-command').value.trim();
|
|
7267
|
+
if (!command) { alert('Command is required for stdio transport'); return; }
|
|
7268
|
+
transport.command = command;
|
|
7269
|
+
const argsStr = document.getElementById('new-server-args').value.trim();
|
|
7270
|
+
if (argsStr) {
|
|
7271
|
+
transport.args = argsStr.split(',').map(s => s.trim()).filter(Boolean);
|
|
7272
|
+
}
|
|
7273
|
+
} else {
|
|
7274
|
+
const url = document.getElementById('new-server-url').value.trim();
|
|
7275
|
+
if (!url) { alert('URL is required for SSE transport'); return; }
|
|
7276
|
+
transport.url = url;
|
|
7277
|
+
}
|
|
7278
|
+
|
|
7279
|
+
addProxyServer({
|
|
7280
|
+
name,
|
|
7281
|
+
transport,
|
|
7282
|
+
enabled: true,
|
|
7283
|
+
default_tier: tier,
|
|
7284
|
+
});
|
|
7285
|
+
|
|
7286
|
+
// Reset form
|
|
7287
|
+
form.style.display = 'none';
|
|
7288
|
+
document.getElementById('new-server-name').value = '';
|
|
7289
|
+
document.getElementById('new-server-command').value = '';
|
|
7290
|
+
document.getElementById('new-server-args').value = '';
|
|
7291
|
+
document.getElementById('new-server-url').value = '';
|
|
7292
|
+
});
|
|
7293
|
+
})();
|
|
7294
|
+
|
|
7295
|
+
// Initialize
|
|
7296
|
+
async function initialize() {
|
|
7297
|
+
if (!AUTH_TOKEN) {
|
|
7298
|
+
redirectToLogin();
|
|
7299
|
+
return;
|
|
7300
|
+
}
|
|
7301
|
+
|
|
7302
|
+
// Initial data fetch
|
|
7303
|
+
await Promise.all([
|
|
7304
|
+
updateSovereignty(),
|
|
7305
|
+
updateIdentity(),
|
|
7306
|
+
updateHandshakes(),
|
|
7307
|
+
updateSHR(),
|
|
7308
|
+
updateStatus(),
|
|
7309
|
+
updateSovereigntyProfile(),
|
|
7310
|
+
loadProxyServers(),
|
|
7311
|
+
]);
|
|
7312
|
+
|
|
7313
|
+
// Setup SSE for real-time updates
|
|
7314
|
+
setupSSE();
|
|
7315
|
+
|
|
7316
|
+
// Refresh status periodically
|
|
7317
|
+
setInterval(updateStatus, 30000);
|
|
7318
|
+
}
|
|
7319
|
+
|
|
7320
|
+
// Start
|
|
7321
|
+
initialize();
|
|
7322
|
+
</script>
|
|
7323
|
+
</body>
|
|
7324
|
+
</html>`;
|
|
7325
|
+
}
|
|
7326
|
+
|
|
7327
|
+
// src/system-prompt-generator.ts
|
|
7328
|
+
var FEATURE_INFO = {
|
|
7329
|
+
audit_logging: {
|
|
7330
|
+
name: "Audit Logging",
|
|
7331
|
+
activeDescription: "All your tool calls are logged to an encrypted audit trail. No action needed \u2014 this is automatic. You can query the log with sanctuary/monitor_audit_log if you need to review past activity.",
|
|
7332
|
+
toolNames: ["sanctuary/monitor_audit_log"],
|
|
7333
|
+
disabledDescription: "audit logging (sanctuary/monitor_audit_log)",
|
|
7334
|
+
usageExample: "Automatic \u2014 every tool call you make is recorded. No explicit action required."
|
|
6569
7335
|
},
|
|
6570
7336
|
injection_detection: {
|
|
6571
7337
|
name: "Injection Detection",
|
|
6572
|
-
activeDescription: "Your tool call arguments are scanned for prompt injection attempts.
|
|
6573
|
-
disabledDescription: "injection detection"
|
|
7338
|
+
activeDescription: "Your tool call arguments are scanned for prompt injection attempts. This is automatic \u2014 no action needed. If injection is detected in your input, the call will be blocked and you will receive an error. Do not retry blocked calls with the same input.",
|
|
7339
|
+
disabledDescription: "injection detection",
|
|
7340
|
+
usageExample: "Automatic \u2014 if a tool call is blocked with an injection alert, do not retry with the same arguments."
|
|
6574
7341
|
},
|
|
6575
7342
|
context_gating: {
|
|
6576
7343
|
name: "Context Gating",
|
|
6577
|
-
activeDescription: "Before
|
|
6578
|
-
toolNames: [
|
|
6579
|
-
|
|
7344
|
+
activeDescription: "Before sending context to any external API (LLM inference, tool APIs, logging services), call sanctuary/context_gate_filter to strip sensitive fields. Use sanctuary/context_gate_set_policy to define filtering rules, or sanctuary/context_gate_apply_template for presets.",
|
|
7345
|
+
toolNames: [
|
|
7346
|
+
"sanctuary/context_gate_filter",
|
|
7347
|
+
"sanctuary/context_gate_set_policy",
|
|
7348
|
+
"sanctuary/context_gate_apply_template",
|
|
7349
|
+
"sanctuary/context_gate_recommend",
|
|
7350
|
+
"sanctuary/context_gate_list_policies"
|
|
7351
|
+
],
|
|
7352
|
+
disabledDescription: "context gating (sanctuary/context_gate_filter)",
|
|
7353
|
+
usageExample: "Before calling an external API, run: sanctuary/context_gate_filter with your context object and policy_id to get a filtered version."
|
|
6580
7354
|
},
|
|
6581
7355
|
approval_gate: {
|
|
6582
7356
|
name: "Approval Gates",
|
|
6583
|
-
activeDescription: "High-risk operations require human approval before execution. Tier 1 operations always require approval
|
|
6584
|
-
disabledDescription: "approval gates"
|
|
7357
|
+
activeDescription: "High-risk operations require human approval before execution. Tier 1 operations (export, import, key rotation, deletion) always require approval. Tier 2 operations trigger approval when anomalous behavior is detected. When an operation is held for approval, you will receive an async response \u2014 wait for the human decision before proceeding.",
|
|
7358
|
+
disabledDescription: "approval gates",
|
|
7359
|
+
usageExample: "When you call a Tier 1 operation (e.g., state_export), expect an async hold. The human operator will approve or deny via the dashboard."
|
|
6585
7360
|
},
|
|
6586
7361
|
zk_proofs: {
|
|
6587
7362
|
name: "Zero-Knowledge Proofs",
|
|
6588
|
-
activeDescription: "You can prove claims about your data without revealing the underlying values. Use sanctuary/zk_commit to create
|
|
6589
|
-
toolNames: [
|
|
6590
|
-
|
|
7363
|
+
activeDescription: "You can prove claims about your data without revealing the underlying values. Use sanctuary/zk_commit to create a Pedersen commitment, sanctuary/zk_prove (Schnorr proof) to prove you know a committed value, and sanctuary/zk_range_prove to prove a value falls within a range \u2014 all without disclosing the actual data. For simpler SHA-256 commitments, use sanctuary/proof_commitment.",
|
|
7364
|
+
toolNames: [
|
|
7365
|
+
"sanctuary/zk_commit",
|
|
7366
|
+
"sanctuary/zk_prove",
|
|
7367
|
+
"sanctuary/zk_range_prove",
|
|
7368
|
+
"sanctuary/proof_commitment"
|
|
7369
|
+
],
|
|
7370
|
+
disabledDescription: "zero-knowledge proofs (sanctuary/zk_commit, sanctuary/zk_prove)",
|
|
7371
|
+
usageExample: "To prove a claim without revealing data: first sanctuary/zk_commit to commit, then sanctuary/zk_prove or sanctuary/zk_range_prove to generate a verifiable proof."
|
|
6591
7372
|
}
|
|
6592
7373
|
};
|
|
6593
7374
|
function generateSystemPrompt(profile) {
|
|
6594
7375
|
const activeFeatures = [];
|
|
6595
7376
|
const inactiveFeatures = [];
|
|
7377
|
+
const activeKeys = [];
|
|
6596
7378
|
const featureKeys = [
|
|
6597
7379
|
"audit_logging",
|
|
6598
7380
|
"injection_detection",
|
|
@@ -6604,6 +7386,7 @@ function generateSystemPrompt(profile) {
|
|
|
6604
7386
|
const featureConfig = profile.features[key];
|
|
6605
7387
|
const info = FEATURE_INFO[key];
|
|
6606
7388
|
if (featureConfig.enabled) {
|
|
7389
|
+
activeKeys.push(key);
|
|
6607
7390
|
let desc = `- ${info.name}: ${info.activeDescription}`;
|
|
6608
7391
|
if (key === "injection_detection" && "sensitivity" in featureConfig && featureConfig.sensitivity) {
|
|
6609
7392
|
desc += ` Sensitivity: ${featureConfig.sensitivity}.`;
|
|
@@ -6616,14 +7399,25 @@ function generateSystemPrompt(profile) {
|
|
|
6616
7399
|
inactiveFeatures.push(info.disabledDescription);
|
|
6617
7400
|
}
|
|
6618
7401
|
}
|
|
6619
|
-
const lines = [
|
|
6620
|
-
|
|
6621
|
-
""
|
|
6622
|
-
|
|
7402
|
+
const lines = [];
|
|
7403
|
+
if (activeKeys.length > 0) {
|
|
7404
|
+
lines.push("QUICK START:");
|
|
7405
|
+
const quickStartItems = buildQuickStart(activeKeys);
|
|
7406
|
+
for (const item of quickStartItems) {
|
|
7407
|
+
lines.push(` ${item}`);
|
|
7408
|
+
}
|
|
7409
|
+
lines.push("");
|
|
7410
|
+
}
|
|
7411
|
+
lines.push(
|
|
7412
|
+
"You are protected by Sanctuary sovereignty infrastructure. The following protections are active:"
|
|
7413
|
+
);
|
|
7414
|
+
lines.push("");
|
|
6623
7415
|
if (activeFeatures.length > 0) {
|
|
6624
7416
|
lines.push(...activeFeatures);
|
|
6625
7417
|
} else {
|
|
6626
|
-
lines.push(
|
|
7418
|
+
lines.push(
|
|
7419
|
+
"- No features are currently enabled. Contact your operator to configure protections."
|
|
7420
|
+
);
|
|
6627
7421
|
}
|
|
6628
7422
|
if (inactiveFeatures.length > 0) {
|
|
6629
7423
|
lines.push("");
|
|
@@ -6633,6 +7427,35 @@ function generateSystemPrompt(profile) {
|
|
|
6633
7427
|
}
|
|
6634
7428
|
return lines.join("\n");
|
|
6635
7429
|
}
|
|
7430
|
+
function buildQuickStart(activeKeys) {
|
|
7431
|
+
const items = [];
|
|
7432
|
+
if (activeKeys.includes("context_gating")) {
|
|
7433
|
+
items.push(
|
|
7434
|
+
"1. ALWAYS call sanctuary/context_gate_filter before sending context to external APIs."
|
|
7435
|
+
);
|
|
7436
|
+
}
|
|
7437
|
+
if (activeKeys.includes("zk_proofs")) {
|
|
7438
|
+
items.push(
|
|
7439
|
+
`${items.length + 1}. Use sanctuary/zk_commit to prove claims without revealing underlying data.`
|
|
7440
|
+
);
|
|
7441
|
+
}
|
|
7442
|
+
if (activeKeys.includes("approval_gate")) {
|
|
7443
|
+
items.push(
|
|
7444
|
+
`${items.length + 1}. High-risk operations will be held for human approval \u2014 expect async responses.`
|
|
7445
|
+
);
|
|
7446
|
+
}
|
|
7447
|
+
if (items.length === 0) {
|
|
7448
|
+
if (activeKeys.includes("audit_logging")) {
|
|
7449
|
+
items.push("1. All tool calls are automatically logged to an encrypted audit trail.");
|
|
7450
|
+
}
|
|
7451
|
+
if (activeKeys.includes("injection_detection")) {
|
|
7452
|
+
items.push(
|
|
7453
|
+
`${items.length + 1}. Tool arguments are scanned for injection \u2014 blocked calls should not be retried.`
|
|
7454
|
+
);
|
|
7455
|
+
}
|
|
7456
|
+
}
|
|
7457
|
+
return items;
|
|
7458
|
+
}
|
|
6636
7459
|
|
|
6637
7460
|
// src/principal-policy/dashboard.ts
|
|
6638
7461
|
var SESSION_TTL_REMOTE_MS = 5 * 60 * 1e3;
|
|
@@ -6655,6 +7478,7 @@ var DashboardApprovalChannel = class {
|
|
|
6655
7478
|
shrOpts = null;
|
|
6656
7479
|
_sanctuaryConfig = null;
|
|
6657
7480
|
profileStore = null;
|
|
7481
|
+
clientManager = null;
|
|
6658
7482
|
dashboardHTML;
|
|
6659
7483
|
loginHTML;
|
|
6660
7484
|
authToken;
|
|
@@ -6676,8 +7500,7 @@ var DashboardApprovalChannel = class {
|
|
|
6676
7500
|
this.sessionTTLMs = isLocalhost ? SESSION_TTL_LOCAL_MS : SESSION_TTL_REMOTE_MS;
|
|
6677
7501
|
this.dashboardHTML = generateDashboardHTML({
|
|
6678
7502
|
timeoutSeconds: config.timeout_seconds,
|
|
6679
|
-
serverVersion: SANCTUARY_VERSION
|
|
6680
|
-
authToken: this.authToken
|
|
7503
|
+
serverVersion: SANCTUARY_VERSION
|
|
6681
7504
|
});
|
|
6682
7505
|
this.loginHTML = generateLoginHTML({ serverVersion: SANCTUARY_VERSION });
|
|
6683
7506
|
this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
|
|
@@ -6695,6 +7518,7 @@ var DashboardApprovalChannel = class {
|
|
|
6695
7518
|
if (deps.shrOpts) this.shrOpts = deps.shrOpts;
|
|
6696
7519
|
if (deps.sanctuaryConfig) this._sanctuaryConfig = deps.sanctuaryConfig;
|
|
6697
7520
|
if (deps.profileStore) this.profileStore = deps.profileStore;
|
|
7521
|
+
if (deps.clientManager) this.clientManager = deps.clientManager;
|
|
6698
7522
|
}
|
|
6699
7523
|
/**
|
|
6700
7524
|
* Mark this dashboard as running in standalone mode.
|
|
@@ -7046,6 +7870,10 @@ var DashboardApprovalChannel = class {
|
|
|
7046
7870
|
this.handleSovereigntyProfileGet(res);
|
|
7047
7871
|
} else if (method === "POST" && url.pathname === "/api/sovereignty-profile") {
|
|
7048
7872
|
this.handleSovereigntyProfileUpdate(req, res);
|
|
7873
|
+
} else if (method === "GET" && url.pathname === "/api/proxy/servers") {
|
|
7874
|
+
this.handleProxyServers(res);
|
|
7875
|
+
} else if (method === "POST" && url.pathname === "/api/proxy/servers") {
|
|
7876
|
+
this.handleProxyServersUpdate(req, res);
|
|
7049
7877
|
} else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
|
|
7050
7878
|
if (!this.checkRateLimit(req, res, "decisions")) return;
|
|
7051
7879
|
const id = url.pathname.slice("/api/approve/".length);
|
|
@@ -7392,6 +8220,85 @@ data: ${JSON.stringify(initData)}
|
|
|
7392
8220
|
}
|
|
7393
8221
|
});
|
|
7394
8222
|
}
|
|
8223
|
+
// ── Proxy Server Handlers ───────────────────────────────────────────
|
|
8224
|
+
/**
|
|
8225
|
+
* GET /api/proxy/servers — list upstream proxy servers and their status.
|
|
8226
|
+
*/
|
|
8227
|
+
handleProxyServers(res) {
|
|
8228
|
+
const profile = this.profileStore?.get();
|
|
8229
|
+
const upstreamServers = profile?.upstream_servers ?? [];
|
|
8230
|
+
const clientStatus = this.clientManager?.getStatus() ?? [];
|
|
8231
|
+
const servers = upstreamServers.map((server) => {
|
|
8232
|
+
const status = clientStatus.find((s) => s.name === server.name);
|
|
8233
|
+
return {
|
|
8234
|
+
name: server.name,
|
|
8235
|
+
transport_type: server.transport.type,
|
|
8236
|
+
enabled: server.enabled,
|
|
8237
|
+
default_tier: server.default_tier,
|
|
8238
|
+
state: status?.state ?? "disconnected",
|
|
8239
|
+
tool_count: status?.tool_count ?? 0,
|
|
8240
|
+
error: status?.error,
|
|
8241
|
+
tool_overrides: server.tool_overrides ?? {}
|
|
8242
|
+
};
|
|
8243
|
+
});
|
|
8244
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
8245
|
+
res.end(JSON.stringify({ servers }));
|
|
8246
|
+
}
|
|
8247
|
+
/**
|
|
8248
|
+
* POST /api/proxy/servers — update upstream server configuration.
|
|
8249
|
+
* This is a dashboard action (human-initiated), so it's allowed with audit logging
|
|
8250
|
+
* rather than requiring Tier 1 approval.
|
|
8251
|
+
*/
|
|
8252
|
+
handleProxyServersUpdate(req, res) {
|
|
8253
|
+
if (!this.profileStore) {
|
|
8254
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
8255
|
+
res.end(JSON.stringify({ error: "Profile store not available" }));
|
|
8256
|
+
return;
|
|
8257
|
+
}
|
|
8258
|
+
let body = "";
|
|
8259
|
+
let destroyed = false;
|
|
8260
|
+
req.on("data", (chunk) => {
|
|
8261
|
+
body += chunk.toString();
|
|
8262
|
+
if (body.length > 16384) {
|
|
8263
|
+
destroyed = true;
|
|
8264
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
8265
|
+
res.end(JSON.stringify({ error: "Request body too large" }));
|
|
8266
|
+
req.destroy();
|
|
8267
|
+
}
|
|
8268
|
+
});
|
|
8269
|
+
req.on("end", async () => {
|
|
8270
|
+
if (destroyed) return;
|
|
8271
|
+
try {
|
|
8272
|
+
const { upstream_servers } = JSON.parse(body);
|
|
8273
|
+
const updated = await this.profileStore.update({ upstream_servers });
|
|
8274
|
+
if (this.auditLog) {
|
|
8275
|
+
this.auditLog.append("l2", "proxy_servers_update_dashboard", "dashboard", {
|
|
8276
|
+
server_count: upstream_servers.length,
|
|
8277
|
+
servers: upstream_servers.map((s) => ({
|
|
8278
|
+
name: s.name,
|
|
8279
|
+
type: s.transport.type,
|
|
8280
|
+
enabled: s.enabled,
|
|
8281
|
+
tier: s.default_tier
|
|
8282
|
+
}))
|
|
8283
|
+
});
|
|
8284
|
+
}
|
|
8285
|
+
if (this.clientManager && updated.upstream_servers) {
|
|
8286
|
+
this.clientManager.configure(updated.upstream_servers).catch(() => {
|
|
8287
|
+
});
|
|
8288
|
+
}
|
|
8289
|
+
this.broadcastSSE("proxy-servers-update", {
|
|
8290
|
+
servers: updated.upstream_servers ?? [],
|
|
8291
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
8292
|
+
});
|
|
8293
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
8294
|
+
res.end(JSON.stringify({ upstream_servers: updated.upstream_servers ?? [] }));
|
|
8295
|
+
} catch (err) {
|
|
8296
|
+
const message = err instanceof Error ? err.message : "Invalid request";
|
|
8297
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
8298
|
+
res.end(JSON.stringify({ error: message }));
|
|
8299
|
+
}
|
|
8300
|
+
});
|
|
8301
|
+
}
|
|
7395
8302
|
// ── SSE Broadcasting ────────────────────────────────────────────────
|
|
7396
8303
|
broadcastSSE(event, data) {
|
|
7397
8304
|
const message = `event: ${event}
|
|
@@ -7748,6 +8655,70 @@ var TOOL_INVOCATION_PATTERNS = [
|
|
|
7748
8655
|
];
|
|
7749
8656
|
var URL_PATTERN = /https?:\/\/[^\s"'<>]+/i;
|
|
7750
8657
|
var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
|
|
8658
|
+
var INVISIBLE_CHARS = [
|
|
8659
|
+
"\u200B",
|
|
8660
|
+
// Zero-width space
|
|
8661
|
+
"\u200C",
|
|
8662
|
+
// Zero-width non-joiner
|
|
8663
|
+
"\u200D",
|
|
8664
|
+
// Zero-width joiner
|
|
8665
|
+
"\uFEFF",
|
|
8666
|
+
// Zero-width no-break space (BOM)
|
|
8667
|
+
"\xAD",
|
|
8668
|
+
// Soft hyphen
|
|
8669
|
+
"\u200E",
|
|
8670
|
+
// Left-to-right mark
|
|
8671
|
+
"\u200F",
|
|
8672
|
+
// Right-to-left mark
|
|
8673
|
+
"\u2060",
|
|
8674
|
+
// Word joiner
|
|
8675
|
+
"\u2061",
|
|
8676
|
+
// Function application
|
|
8677
|
+
"\u2062",
|
|
8678
|
+
// Invisible times
|
|
8679
|
+
"\u2063",
|
|
8680
|
+
// Invisible separator
|
|
8681
|
+
"\u2064",
|
|
8682
|
+
// Invisible plus
|
|
8683
|
+
"\u180E",
|
|
8684
|
+
// Mongolian vowel separator
|
|
8685
|
+
"\u034F",
|
|
8686
|
+
// Combining grapheme joiner
|
|
8687
|
+
"\u061C",
|
|
8688
|
+
// Arabic letter mark
|
|
8689
|
+
"\u115F",
|
|
8690
|
+
// Hangul choseong filler
|
|
8691
|
+
"\u1160",
|
|
8692
|
+
// Hangul jungseong filler
|
|
8693
|
+
"\u17B4",
|
|
8694
|
+
// Khmer vowel inherent AQ
|
|
8695
|
+
"\u17B5",
|
|
8696
|
+
// Khmer vowel inherent AA
|
|
8697
|
+
"\u3164",
|
|
8698
|
+
// Hangul filler
|
|
8699
|
+
"\uFFA0",
|
|
8700
|
+
// Halfwidth hangul filler
|
|
8701
|
+
"\u202A",
|
|
8702
|
+
// Left-to-Right Embedding (LRE)
|
|
8703
|
+
"\u202B",
|
|
8704
|
+
// Right-to-Left Embedding (RLE)
|
|
8705
|
+
"\u202C",
|
|
8706
|
+
// Pop Directional Formatting (PDF)
|
|
8707
|
+
"\u202D",
|
|
8708
|
+
// Left-to-Right Override (LRO)
|
|
8709
|
+
"\u202E",
|
|
8710
|
+
// Right-to-Left Override (RLO)
|
|
8711
|
+
"\u2066",
|
|
8712
|
+
// Left-to-Right Isolate (LRI)
|
|
8713
|
+
"\u2067",
|
|
8714
|
+
// Right-to-Left Isolate (RLI)
|
|
8715
|
+
"\u2068",
|
|
8716
|
+
// First Strong Isolate (FSI)
|
|
8717
|
+
"\u2069"
|
|
8718
|
+
// Pop Directional Isolate (PDI)
|
|
8719
|
+
];
|
|
8720
|
+
var VARIATION_SELECTOR_RANGE_START = 65024;
|
|
8721
|
+
var VARIATION_SELECTOR_RANGE_END = 65039;
|
|
7751
8722
|
var ZERO_WIDTH_CHARS = [
|
|
7752
8723
|
"\u200B",
|
|
7753
8724
|
// Zero-width space
|
|
@@ -7758,6 +8729,66 @@ var ZERO_WIDTH_CHARS = [
|
|
|
7758
8729
|
"\uFEFF"
|
|
7759
8730
|
// Zero-width no-break space
|
|
7760
8731
|
];
|
|
8732
|
+
var BASE64_STANDARD_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
8733
|
+
var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+={0,2}$/;
|
|
8734
|
+
var BASE64_BLOCK_PATTERN = /[A-Za-z0-9+/]{20,}={0,2}/g;
|
|
8735
|
+
var HEX_ENCODED_PATTERN = /(?:0x)?[0-9a-fA-F]{20,}/g;
|
|
8736
|
+
var HTML_ENTITY_PATTERN = /&#(?:x[0-9a-fA-F]{2,4}|[0-9]{2,5});/g;
|
|
8737
|
+
var URL_ENCODED_PATTERN = /(?:%[0-9a-fA-F]{2}){4,}/g;
|
|
8738
|
+
var SECRET_PATTERNS = [
|
|
8739
|
+
{ pattern: /sk-[a-zA-Z0-9]{20,}/, name: "openai_api_key" },
|
|
8740
|
+
{ pattern: /sk-ant-[a-zA-Z0-9_-]{20,}/, name: "anthropic_api_key" },
|
|
8741
|
+
{ pattern: /ghp_[a-zA-Z0-9]{36,}/, name: "github_pat" },
|
|
8742
|
+
{ pattern: /gho_[a-zA-Z0-9]{36,}/, name: "github_oauth" },
|
|
8743
|
+
{ pattern: /ghs_[a-zA-Z0-9]{36,}/, name: "github_app" },
|
|
8744
|
+
{ pattern: /github_pat_[a-zA-Z0-9_]{22,}/, name: "github_fine_grained_pat" },
|
|
8745
|
+
{ pattern: /AKIA[0-9A-Z]{16}/, name: "aws_access_key" },
|
|
8746
|
+
{ pattern: /xoxb-[0-9]{10,}-[a-zA-Z0-9-]+/, name: "slack_bot_token" },
|
|
8747
|
+
{ pattern: /xoxp-[0-9]{10,}-[a-zA-Z0-9-]+/, name: "slack_user_token" },
|
|
8748
|
+
{ pattern: /xapp-[0-9]-[A-Z0-9]+-[0-9]+-[a-z0-9]+/, name: "slack_app_token" },
|
|
8749
|
+
{ pattern: /(?:Bearer|bearer)\s+[a-zA-Z0-9._~+/=-]{20,}/, name: "bearer_token" },
|
|
8750
|
+
{ pattern: /glpat-[a-zA-Z0-9_-]{20,}/, name: "gitlab_pat" },
|
|
8751
|
+
{ pattern: /npm_[a-zA-Z0-9]{36,}/, name: "npm_token" },
|
|
8752
|
+
{ pattern: /pypi-[a-zA-Z0-9_-]{20,}/, name: "pypi_token" },
|
|
8753
|
+
{ pattern: /AIza[a-zA-Z0-9_-]{35}/, name: "google_api_key" },
|
|
8754
|
+
{ pattern: /SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}/, name: "sendgrid_api_key" },
|
|
8755
|
+
{ pattern: /sq0[a-z]{3}-[a-zA-Z0-9_-]{22,}/, name: "square_api_key" },
|
|
8756
|
+
{ pattern: /sk_live_[a-zA-Z0-9]{24,}/, name: "stripe_secret_key" },
|
|
8757
|
+
{ pattern: /rk_live_[a-zA-Z0-9]{24,}/, name: "stripe_restricted_key" },
|
|
8758
|
+
{ pattern: /(?:-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----)/, name: "private_key_pem" }
|
|
8759
|
+
];
|
|
8760
|
+
var MARKDOWN_IMAGE_EXFIL_PATTERN = /!\[[^\]]*\]\(https?:\/\/[^)]*[?&](?:data|secret|key|token|password|auth|session|cookie|api_key|access_token)=/i;
|
|
8761
|
+
var INTERNAL_PATH_PATTERNS = [
|
|
8762
|
+
/\/home\/[a-zA-Z0-9_.-]+\//,
|
|
8763
|
+
/\/Users\/[a-zA-Z0-9_.-]+\//,
|
|
8764
|
+
/[A-Z]:\\(?:Users|Documents|Program Files)\\/,
|
|
8765
|
+
/~\/\.(?:ssh|aws|config|gnupg|sanctuary)\//,
|
|
8766
|
+
/\/etc\/(?:passwd|shadow|hosts|ssh)/,
|
|
8767
|
+
/\/var\/(?:log|run|lib)\//
|
|
8768
|
+
];
|
|
8769
|
+
var PRIVATE_NETWORK_PATTERNS = [
|
|
8770
|
+
/(?:^|\s|\/\/)(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3})/,
|
|
8771
|
+
/(?:^|\s|\/\/)(?:172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})/,
|
|
8772
|
+
/(?:^|\s|\/\/)(?:192\.168\.\d{1,3}\.\d{1,3})/,
|
|
8773
|
+
/(?:^|\s|\/\/)localhost(?::\d+)?/,
|
|
8774
|
+
/(?:^|\s|\/\/)127\.0\.0\.1/,
|
|
8775
|
+
/(?:^|\s|\/\/)0\.0\.0\.0/,
|
|
8776
|
+
/(?:^|\s|\/\/)\[?::1\]?/
|
|
8777
|
+
];
|
|
8778
|
+
var OUTPUT_ROLE_MARKER_PATTERNS = [
|
|
8779
|
+
/\bsystem\s*:/i,
|
|
8780
|
+
/\[INST\]/,
|
|
8781
|
+
/\[\/INST\]/,
|
|
8782
|
+
/<\|im_start\|>/,
|
|
8783
|
+
/<\|im_end\|>/,
|
|
8784
|
+
/<\|system\|>/,
|
|
8785
|
+
/<\|user\|>/,
|
|
8786
|
+
/<\|assistant\|>/,
|
|
8787
|
+
/<<\s*SYS\s*>>/,
|
|
8788
|
+
/<<\s*\/SYS\s*>>/,
|
|
8789
|
+
/\[SYSTEM\]/,
|
|
8790
|
+
/### (?:System|Human|Assistant):/
|
|
8791
|
+
];
|
|
7761
8792
|
var InjectionDetector = class {
|
|
7762
8793
|
config;
|
|
7763
8794
|
stats = {
|
|
@@ -7814,6 +8845,50 @@ var InjectionDetector = class {
|
|
|
7814
8845
|
recommendation
|
|
7815
8846
|
};
|
|
7816
8847
|
}
|
|
8848
|
+
/**
|
|
8849
|
+
* SEC-035: Scan outbound content for secret leaks, data exfiltration,
|
|
8850
|
+
* internal path exposure, and injection artifact survival.
|
|
8851
|
+
*
|
|
8852
|
+
* @param content The outbound content string to scan
|
|
8853
|
+
* @returns DetectionResult with outbound-specific signal types
|
|
8854
|
+
*/
|
|
8855
|
+
scanOutbound(content) {
|
|
8856
|
+
this.stats.total_scans++;
|
|
8857
|
+
if (!this.config.enabled) {
|
|
8858
|
+
return {
|
|
8859
|
+
flagged: false,
|
|
8860
|
+
confidence: 0,
|
|
8861
|
+
signals: [],
|
|
8862
|
+
recommendation: "allow"
|
|
8863
|
+
};
|
|
8864
|
+
}
|
|
8865
|
+
const signals = [];
|
|
8866
|
+
this.detectSecretPatterns(content, signals);
|
|
8867
|
+
this.detectOutboundExfiltration(content, signals);
|
|
8868
|
+
this.detectInternalPathLeaks(content, signals);
|
|
8869
|
+
this.detectPrivateNetworkLeaks(content, signals);
|
|
8870
|
+
this.detectOutputRoleMarkers(content, signals);
|
|
8871
|
+
const flagged = signals.length > 0;
|
|
8872
|
+
if (flagged) {
|
|
8873
|
+
this.stats.total_flags++;
|
|
8874
|
+
}
|
|
8875
|
+
for (const sig of signals) {
|
|
8876
|
+
this.stats.signals_by_type[sig.type] = (this.stats.signals_by_type[sig.type] ?? 0) + 1;
|
|
8877
|
+
}
|
|
8878
|
+
const recommendation = this.computeRecommendation(
|
|
8879
|
+
signals,
|
|
8880
|
+
this.config.sensitivity
|
|
8881
|
+
);
|
|
8882
|
+
if (recommendation === "block") {
|
|
8883
|
+
this.stats.total_blocks++;
|
|
8884
|
+
}
|
|
8885
|
+
return {
|
|
8886
|
+
flagged,
|
|
8887
|
+
confidence: this.computeConfidence(signals),
|
|
8888
|
+
signals,
|
|
8889
|
+
recommendation
|
|
8890
|
+
};
|
|
8891
|
+
}
|
|
7817
8892
|
/**
|
|
7818
8893
|
* Recursively scan a value and all nested values.
|
|
7819
8894
|
*/
|
|
@@ -7842,14 +8917,40 @@ var InjectionDetector = class {
|
|
|
7842
8917
|
return;
|
|
7843
8918
|
}
|
|
7844
8919
|
const location = path || "root";
|
|
7845
|
-
const
|
|
7846
|
-
if (
|
|
8920
|
+
const invisibleCount = this.countInvisibleChars(value);
|
|
8921
|
+
if (invisibleCount > 3) {
|
|
8922
|
+
signals.push({
|
|
8923
|
+
type: "unicode_smuggling",
|
|
8924
|
+
pattern: `invisible_chars_count_${invisibleCount}`,
|
|
8925
|
+
location,
|
|
8926
|
+
severity: "high"
|
|
8927
|
+
});
|
|
8928
|
+
}
|
|
8929
|
+
this.detectTokenBudgetAttack(value, location, signals);
|
|
8930
|
+
const stripped = this.stripInvisibleChars(value);
|
|
8931
|
+
const nfkcOnly = stripped.normalize("NFKC");
|
|
8932
|
+
const normalized = this.normalizeConfusables(nfkcOnly);
|
|
8933
|
+
if (nfkcOnly !== stripped) {
|
|
8934
|
+
signals.push({
|
|
8935
|
+
type: "encoding_evasion",
|
|
8936
|
+
pattern: "unicode_normalization_delta",
|
|
8937
|
+
location,
|
|
8938
|
+
severity: "medium"
|
|
8939
|
+
});
|
|
8940
|
+
}
|
|
8941
|
+
if (normalized !== nfkcOnly) {
|
|
7847
8942
|
signals.push({
|
|
7848
8943
|
type: "encoding_evasion",
|
|
7849
8944
|
pattern: "unicode_normalization_delta",
|
|
7850
8945
|
location,
|
|
7851
8946
|
severity: "medium"
|
|
7852
8947
|
});
|
|
8948
|
+
signals.push({
|
|
8949
|
+
type: "homoglyph_attack",
|
|
8950
|
+
pattern: "confusable_substitution",
|
|
8951
|
+
location,
|
|
8952
|
+
severity: "high"
|
|
8953
|
+
});
|
|
7853
8954
|
}
|
|
7854
8955
|
for (const pattern of ROLE_OVERRIDE_PATTERNS) {
|
|
7855
8956
|
if (pattern.test(normalized)) {
|
|
@@ -7887,21 +8988,363 @@ var InjectionDetector = class {
|
|
|
7887
8988
|
}
|
|
7888
8989
|
}
|
|
7889
8990
|
this.detectEncodingEvasion(value, location, signals);
|
|
8991
|
+
this.detectEncodedPayloads(value, location, signals);
|
|
7890
8992
|
this.detectDataExfiltration(value, location, signals);
|
|
7891
8993
|
this.detectPromptStuffing(value, location, signals);
|
|
7892
8994
|
}
|
|
8995
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
8996
|
+
// SEC-034: Unicode sanitization helpers
|
|
8997
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
7893
8998
|
/**
|
|
7894
|
-
*
|
|
8999
|
+
* Count invisible Unicode characters in a string.
|
|
9000
|
+
* Includes zero-width chars, soft hyphens, directional marks,
|
|
9001
|
+
* variation selectors, and other invisible categories.
|
|
7895
9002
|
*/
|
|
7896
|
-
|
|
7897
|
-
|
|
9003
|
+
countInvisibleChars(value) {
|
|
9004
|
+
let count = 0;
|
|
9005
|
+
for (const ch of value) {
|
|
9006
|
+
const cp = ch.codePointAt(0);
|
|
9007
|
+
if (cp === void 0) continue;
|
|
9008
|
+
if (INVISIBLE_CHARS.includes(ch)) {
|
|
9009
|
+
count++;
|
|
9010
|
+
continue;
|
|
9011
|
+
}
|
|
9012
|
+
if (cp >= VARIATION_SELECTOR_RANGE_START && cp <= VARIATION_SELECTOR_RANGE_END) {
|
|
9013
|
+
count++;
|
|
9014
|
+
continue;
|
|
9015
|
+
}
|
|
9016
|
+
if (cp >= 917760 && cp <= 917999) {
|
|
9017
|
+
count++;
|
|
9018
|
+
continue;
|
|
9019
|
+
}
|
|
9020
|
+
if (cp >= 917505 && cp <= 917631) {
|
|
9021
|
+
count++;
|
|
9022
|
+
continue;
|
|
9023
|
+
}
|
|
9024
|
+
if (cp >= 65529 && cp <= 65531) {
|
|
9025
|
+
count++;
|
|
9026
|
+
continue;
|
|
9027
|
+
}
|
|
9028
|
+
}
|
|
9029
|
+
return count;
|
|
9030
|
+
}
|
|
9031
|
+
/**
|
|
9032
|
+
* Strip invisible characters from a string for clean pattern matching.
|
|
9033
|
+
* Returns a new string with all invisible chars removed.
|
|
9034
|
+
*/
|
|
9035
|
+
stripInvisibleChars(value) {
|
|
9036
|
+
const chars = [];
|
|
9037
|
+
for (const ch of value) {
|
|
9038
|
+
const cp = ch.codePointAt(0);
|
|
9039
|
+
if (cp === void 0) continue;
|
|
9040
|
+
if (INVISIBLE_CHARS.includes(ch)) continue;
|
|
9041
|
+
if (cp >= VARIATION_SELECTOR_RANGE_START && cp <= VARIATION_SELECTOR_RANGE_END) continue;
|
|
9042
|
+
if (cp >= 917760 && cp <= 917999) continue;
|
|
9043
|
+
if (cp >= 917505 && cp <= 917631) continue;
|
|
9044
|
+
if (cp >= 65529 && cp <= 65531) continue;
|
|
9045
|
+
chars.push(ch);
|
|
9046
|
+
}
|
|
9047
|
+
return chars.join("");
|
|
9048
|
+
}
|
|
9049
|
+
/**
|
|
9050
|
+
* SEC-034: Token budget attack detection.
|
|
9051
|
+
* Some Unicode sequences expand dramatically during tokenization (e.g., CJK
|
|
9052
|
+
* ideographs, combining characters, emoji sequences). If the estimated token
|
|
9053
|
+
* cost per character is anomalously high, this may be a wallet-drain payload.
|
|
9054
|
+
*
|
|
9055
|
+
* Heuristic: count chars that typically tokenize into multiple tokens.
|
|
9056
|
+
* If the ratio of estimated tokens to char count exceeds 3x, flag it.
|
|
9057
|
+
*/
|
|
9058
|
+
detectTokenBudgetAttack(value, path, signals) {
|
|
9059
|
+
if (value.length < 20) return;
|
|
9060
|
+
const MAX_ANALYSIS_LENGTH = 1e6;
|
|
9061
|
+
if (value.length > MAX_ANALYSIS_LENGTH) {
|
|
9062
|
+
value = value.substring(0, MAX_ANALYSIS_LENGTH);
|
|
9063
|
+
}
|
|
9064
|
+
let estimatedTokens = 0;
|
|
9065
|
+
for (const ch of value) {
|
|
9066
|
+
const cp = ch.codePointAt(0);
|
|
9067
|
+
if (cp === void 0) continue;
|
|
9068
|
+
if (cp <= 127) {
|
|
9069
|
+
estimatedTokens += 0.25;
|
|
9070
|
+
} else if (cp <= 2047) {
|
|
9071
|
+
estimatedTokens += 0.5;
|
|
9072
|
+
} else if (cp <= 65535) {
|
|
9073
|
+
estimatedTokens += 1.5;
|
|
9074
|
+
} else {
|
|
9075
|
+
estimatedTokens += 2.5;
|
|
9076
|
+
}
|
|
9077
|
+
}
|
|
9078
|
+
let charCount = 0;
|
|
9079
|
+
for (const _ch of value) {
|
|
9080
|
+
charCount++;
|
|
9081
|
+
}
|
|
9082
|
+
const ratio = estimatedTokens / charCount;
|
|
9083
|
+
if (ratio > 3) {
|
|
7898
9084
|
signals.push({
|
|
7899
|
-
type: "
|
|
7900
|
-
pattern:
|
|
7901
|
-
location: path
|
|
9085
|
+
type: "token_budget_attack",
|
|
9086
|
+
pattern: `token_char_ratio_${ratio.toFixed(2)}`,
|
|
9087
|
+
location: path,
|
|
7902
9088
|
severity: "medium"
|
|
7903
9089
|
});
|
|
7904
9090
|
}
|
|
9091
|
+
}
|
|
9092
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9093
|
+
// SEC-034: Encoded payload detection and re-scanning
|
|
9094
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9095
|
+
/**
|
|
9096
|
+
* Detect encoded content (base64, hex, HTML entities, URL encoding),
|
|
9097
|
+
* decode it, and re-scan the decoded content through injection patterns.
|
|
9098
|
+
* If the decoded content contains injection patterns, flag as encoding_evasion.
|
|
9099
|
+
*/
|
|
9100
|
+
detectEncodedPayloads(value, path, signals) {
|
|
9101
|
+
const decodedParts = [];
|
|
9102
|
+
const base64Matches = value.match(BASE64_BLOCK_PATTERN);
|
|
9103
|
+
if (base64Matches) {
|
|
9104
|
+
for (const match of base64Matches) {
|
|
9105
|
+
const decoded = this.safeBase64Decode(match);
|
|
9106
|
+
if (decoded !== null) {
|
|
9107
|
+
decodedParts.push(decoded);
|
|
9108
|
+
}
|
|
9109
|
+
}
|
|
9110
|
+
}
|
|
9111
|
+
const hexMatches = value.match(HEX_ENCODED_PATTERN);
|
|
9112
|
+
if (hexMatches) {
|
|
9113
|
+
for (const match of hexMatches) {
|
|
9114
|
+
const decoded = this.safeHexDecode(match);
|
|
9115
|
+
if (decoded !== null) {
|
|
9116
|
+
decodedParts.push(decoded);
|
|
9117
|
+
}
|
|
9118
|
+
}
|
|
9119
|
+
}
|
|
9120
|
+
if (HTML_ENTITY_PATTERN.test(value)) {
|
|
9121
|
+
const decoded = this.decodeHtmlEntities(value);
|
|
9122
|
+
if (decoded !== value) {
|
|
9123
|
+
decodedParts.push(decoded);
|
|
9124
|
+
}
|
|
9125
|
+
}
|
|
9126
|
+
const urlMatches = value.match(URL_ENCODED_PATTERN);
|
|
9127
|
+
if (urlMatches) {
|
|
9128
|
+
for (const match of urlMatches) {
|
|
9129
|
+
const decoded = this.safeUrlDecode(match);
|
|
9130
|
+
if (decoded !== null && decoded !== match) {
|
|
9131
|
+
decodedParts.push(decoded);
|
|
9132
|
+
}
|
|
9133
|
+
}
|
|
9134
|
+
}
|
|
9135
|
+
for (const decoded of decodedParts) {
|
|
9136
|
+
if (this.containsInjectionPatterns(decoded)) {
|
|
9137
|
+
signals.push({
|
|
9138
|
+
type: "encoding_evasion",
|
|
9139
|
+
pattern: "encoded_injection_payload",
|
|
9140
|
+
location: path,
|
|
9141
|
+
severity: "high"
|
|
9142
|
+
});
|
|
9143
|
+
return;
|
|
9144
|
+
}
|
|
9145
|
+
}
|
|
9146
|
+
}
|
|
9147
|
+
/**
|
|
9148
|
+
* Check if a string contains any injection patterns (role override or security bypass).
|
|
9149
|
+
*/
|
|
9150
|
+
containsInjectionPatterns(value) {
|
|
9151
|
+
const normalized = this.normalizeConfusables(value.normalize("NFKC"));
|
|
9152
|
+
for (const pattern of ROLE_OVERRIDE_PATTERNS) {
|
|
9153
|
+
if (pattern.test(normalized)) return true;
|
|
9154
|
+
}
|
|
9155
|
+
for (const pattern of SECURITY_BYPASS_PATTERNS) {
|
|
9156
|
+
if (pattern.test(normalized)) return true;
|
|
9157
|
+
}
|
|
9158
|
+
return false;
|
|
9159
|
+
}
|
|
9160
|
+
/**
|
|
9161
|
+
* Safely decode a base64 string. Returns null if it's not valid base64
|
|
9162
|
+
* or doesn't decode to a meaningful string.
|
|
9163
|
+
*/
|
|
9164
|
+
safeBase64Decode(value) {
|
|
9165
|
+
try {
|
|
9166
|
+
const cleaned = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
9167
|
+
const padded = cleaned + "=".repeat((4 - cleaned.length % 4) % 4);
|
|
9168
|
+
if (!BASE64_STANDARD_PATTERN.test(padded)) return null;
|
|
9169
|
+
const decoded = Buffer.from(padded, "base64").toString("utf-8");
|
|
9170
|
+
if (this.looksLikeText(decoded)) {
|
|
9171
|
+
return decoded;
|
|
9172
|
+
}
|
|
9173
|
+
return null;
|
|
9174
|
+
} catch {
|
|
9175
|
+
return null;
|
|
9176
|
+
}
|
|
9177
|
+
}
|
|
9178
|
+
/**
|
|
9179
|
+
* Safely decode a hex string. Returns null on failure.
|
|
9180
|
+
*/
|
|
9181
|
+
safeHexDecode(value) {
|
|
9182
|
+
try {
|
|
9183
|
+
const hex = value.startsWith("0x") ? value.slice(2) : value;
|
|
9184
|
+
if (hex.length % 2 !== 0) return null;
|
|
9185
|
+
const decoded = Buffer.from(hex, "hex").toString("utf-8");
|
|
9186
|
+
if (this.looksLikeText(decoded)) {
|
|
9187
|
+
return decoded;
|
|
9188
|
+
}
|
|
9189
|
+
return null;
|
|
9190
|
+
} catch {
|
|
9191
|
+
return null;
|
|
9192
|
+
}
|
|
9193
|
+
}
|
|
9194
|
+
/**
|
|
9195
|
+
* Decode HTML numeric entities (&#xHH; and &#DDD;) in a string.
|
|
9196
|
+
*/
|
|
9197
|
+
decodeHtmlEntities(value) {
|
|
9198
|
+
return value.replace(/&#x([0-9a-fA-F]{2,4});/g, (_match, hex) => {
|
|
9199
|
+
try {
|
|
9200
|
+
return String.fromCodePoint(parseInt(hex, 16));
|
|
9201
|
+
} catch {
|
|
9202
|
+
return _match;
|
|
9203
|
+
}
|
|
9204
|
+
}).replace(/&#([0-9]{2,5});/g, (_match, dec) => {
|
|
9205
|
+
try {
|
|
9206
|
+
const cp = parseInt(dec, 10);
|
|
9207
|
+
if (cp > 1114111) return _match;
|
|
9208
|
+
return String.fromCodePoint(cp);
|
|
9209
|
+
} catch {
|
|
9210
|
+
return _match;
|
|
9211
|
+
}
|
|
9212
|
+
});
|
|
9213
|
+
}
|
|
9214
|
+
/**
|
|
9215
|
+
* Safely decode a URL-encoded string. Returns null on failure.
|
|
9216
|
+
*/
|
|
9217
|
+
safeUrlDecode(value) {
|
|
9218
|
+
try {
|
|
9219
|
+
return decodeURIComponent(value);
|
|
9220
|
+
} catch {
|
|
9221
|
+
return null;
|
|
9222
|
+
}
|
|
9223
|
+
}
|
|
9224
|
+
/**
|
|
9225
|
+
* Heuristic: does this look like readable text (vs. binary garbage)?
|
|
9226
|
+
* Checks that most characters are printable ASCII or common Unicode.
|
|
9227
|
+
*/
|
|
9228
|
+
looksLikeText(value) {
|
|
9229
|
+
if (value.length === 0) return false;
|
|
9230
|
+
let printable = 0;
|
|
9231
|
+
for (let i = 0; i < value.length; i++) {
|
|
9232
|
+
const code = value.charCodeAt(i);
|
|
9233
|
+
if (code >= 32 && code <= 126 || code === 10 || code === 13 || code === 9) {
|
|
9234
|
+
printable++;
|
|
9235
|
+
} else if (code >= 128) {
|
|
9236
|
+
if (code < 160) continue;
|
|
9237
|
+
printable++;
|
|
9238
|
+
}
|
|
9239
|
+
}
|
|
9240
|
+
return printable / value.length > 0.7;
|
|
9241
|
+
}
|
|
9242
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9243
|
+
// SEC-035: Outbound content scanning helpers
|
|
9244
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9245
|
+
/**
|
|
9246
|
+
* Detect API keys and secrets in outbound content.
|
|
9247
|
+
*/
|
|
9248
|
+
detectSecretPatterns(content, signals) {
|
|
9249
|
+
for (const { pattern, name } of SECRET_PATTERNS) {
|
|
9250
|
+
if (pattern.test(content)) {
|
|
9251
|
+
signals.push({
|
|
9252
|
+
type: "secret_leak",
|
|
9253
|
+
pattern: name,
|
|
9254
|
+
location: "outbound",
|
|
9255
|
+
severity: "high"
|
|
9256
|
+
});
|
|
9257
|
+
}
|
|
9258
|
+
}
|
|
9259
|
+
}
|
|
9260
|
+
/**
|
|
9261
|
+
* Detect data exfiltration via markdown images with data-carrying query params.
|
|
9262
|
+
*/
|
|
9263
|
+
detectOutboundExfiltration(content, signals) {
|
|
9264
|
+
if (MARKDOWN_IMAGE_EXFIL_PATTERN.test(content)) {
|
|
9265
|
+
signals.push({
|
|
9266
|
+
type: "data_exfiltration",
|
|
9267
|
+
pattern: "markdown_image_exfil",
|
|
9268
|
+
location: "outbound",
|
|
9269
|
+
severity: "high"
|
|
9270
|
+
});
|
|
9271
|
+
}
|
|
9272
|
+
}
|
|
9273
|
+
/**
|
|
9274
|
+
* Detect internal filesystem path leaks in outbound content.
|
|
9275
|
+
*/
|
|
9276
|
+
detectInternalPathLeaks(content, signals) {
|
|
9277
|
+
for (const pattern of INTERNAL_PATH_PATTERNS) {
|
|
9278
|
+
if (pattern.test(content)) {
|
|
9279
|
+
signals.push({
|
|
9280
|
+
type: "internal_path_leak",
|
|
9281
|
+
pattern: pattern.source,
|
|
9282
|
+
location: "outbound",
|
|
9283
|
+
severity: "medium"
|
|
9284
|
+
});
|
|
9285
|
+
return;
|
|
9286
|
+
}
|
|
9287
|
+
}
|
|
9288
|
+
}
|
|
9289
|
+
/**
|
|
9290
|
+
* Detect private IP addresses and localhost references in outbound content.
|
|
9291
|
+
*/
|
|
9292
|
+
detectPrivateNetworkLeaks(content, signals) {
|
|
9293
|
+
for (const pattern of PRIVATE_NETWORK_PATTERNS) {
|
|
9294
|
+
if (pattern.test(content)) {
|
|
9295
|
+
signals.push({
|
|
9296
|
+
type: "private_network_leak",
|
|
9297
|
+
pattern: pattern.source,
|
|
9298
|
+
location: "outbound",
|
|
9299
|
+
severity: "medium"
|
|
9300
|
+
});
|
|
9301
|
+
return;
|
|
9302
|
+
}
|
|
9303
|
+
}
|
|
9304
|
+
}
|
|
9305
|
+
/**
|
|
9306
|
+
* Detect role markers / prompt template artifacts in outbound content.
|
|
9307
|
+
* These should never appear in agent output — their presence indicates
|
|
9308
|
+
* injection artifact survival.
|
|
9309
|
+
*/
|
|
9310
|
+
detectOutputRoleMarkers(content, signals) {
|
|
9311
|
+
for (const pattern of OUTPUT_ROLE_MARKER_PATTERNS) {
|
|
9312
|
+
if (pattern.test(content)) {
|
|
9313
|
+
signals.push({
|
|
9314
|
+
type: "injection_artifact",
|
|
9315
|
+
pattern: pattern.source,
|
|
9316
|
+
location: "outbound",
|
|
9317
|
+
severity: "high"
|
|
9318
|
+
});
|
|
9319
|
+
return;
|
|
9320
|
+
}
|
|
9321
|
+
}
|
|
9322
|
+
}
|
|
9323
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9324
|
+
// Existing detection methods (enhanced)
|
|
9325
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9326
|
+
/**
|
|
9327
|
+
* Detect base64 strings, base64url, and zero-width character evasion.
|
|
9328
|
+
*/
|
|
9329
|
+
detectEncodingEvasion(value, path, signals) {
|
|
9330
|
+
const trimmed = value.trim();
|
|
9331
|
+
if (value.length > 50) {
|
|
9332
|
+
if (BASE64_STANDARD_PATTERN.test(trimmed)) {
|
|
9333
|
+
signals.push({
|
|
9334
|
+
type: "encoding_evasion",
|
|
9335
|
+
pattern: "base64_string",
|
|
9336
|
+
location: path || "root",
|
|
9337
|
+
severity: "medium"
|
|
9338
|
+
});
|
|
9339
|
+
} else if (BASE64URL_PATTERN.test(trimmed) && /[_-]/.test(trimmed)) {
|
|
9340
|
+
signals.push({
|
|
9341
|
+
type: "encoding_evasion",
|
|
9342
|
+
pattern: "base64url_string",
|
|
9343
|
+
location: path || "root",
|
|
9344
|
+
severity: "medium"
|
|
9345
|
+
});
|
|
9346
|
+
}
|
|
9347
|
+
}
|
|
7905
9348
|
let zeroWidthCount = 0;
|
|
7906
9349
|
for (const char of ZERO_WIDTH_CHARS) {
|
|
7907
9350
|
zeroWidthCount += (value.match(new RegExp(char, "g")) || []).length;
|
|
@@ -8080,62 +9523,89 @@ var InjectionDetector = class {
|
|
|
8080
9523
|
return structuredFields.some((p) => p.test(path));
|
|
8081
9524
|
}
|
|
8082
9525
|
/**
|
|
8083
|
-
* SEC-032: Map common cross-script confusable characters to their
|
|
8084
|
-
* NFKC normalization handles fullwidth and compatibility
|
|
8085
|
-
* Cyrillic/Greek lookalikes to
|
|
8086
|
-
*
|
|
9526
|
+
* SEC-032/SEC-034: Map common cross-script confusable characters to their
|
|
9527
|
+
* Latin equivalents. NFKC normalization handles fullwidth and compatibility
|
|
9528
|
+
* forms, but does NOT map Cyrillic/Greek/Armenian/Georgian lookalikes to
|
|
9529
|
+
* Latin (they're distinct codepoints by design).
|
|
9530
|
+
*
|
|
9531
|
+
* Extended to 50+ confusable pairs covering Cyrillic, Greek, Armenian,
|
|
9532
|
+
* Georgian, Cherokee, and mathematical/symbol lookalikes.
|
|
8087
9533
|
*/
|
|
8088
9534
|
normalizeConfusables(value) {
|
|
8089
9535
|
const confusables = {
|
|
8090
|
-
// Cyrillic → Latin
|
|
9536
|
+
// ── Cyrillic → Latin ──────────────────────────────────────────────
|
|
8091
9537
|
"\u0410": "A",
|
|
8092
9538
|
"\u0430": "a",
|
|
8093
9539
|
// А а
|
|
8094
9540
|
"\u0412": "B",
|
|
8095
9541
|
"\u0432": "b",
|
|
8096
|
-
// В
|
|
9542
|
+
// В в (visual approximation)
|
|
8097
9543
|
"\u0421": "C",
|
|
8098
9544
|
"\u0441": "c",
|
|
8099
9545
|
// С с
|
|
9546
|
+
"\u0414": "D",
|
|
9547
|
+
// Д (visual approximation)
|
|
8100
9548
|
"\u0415": "E",
|
|
8101
9549
|
"\u0435": "e",
|
|
8102
9550
|
// Е е
|
|
8103
9551
|
"\u041D": "H",
|
|
8104
9552
|
"\u043D": "h",
|
|
8105
|
-
// Н
|
|
9553
|
+
// Н н (visual approximation)
|
|
9554
|
+
"\u0406": "I",
|
|
9555
|
+
"\u0456": "i",
|
|
9556
|
+
// І і (Ukrainian I)
|
|
9557
|
+
"\u0408": "J",
|
|
9558
|
+
// Ј (Serbian Je)
|
|
8106
9559
|
"\u041A": "K",
|
|
8107
9560
|
"\u043A": "k",
|
|
8108
|
-
// К к (
|
|
9561
|
+
// К к (visual approximation)
|
|
8109
9562
|
"\u041C": "M",
|
|
8110
9563
|
"\u043C": "m",
|
|
8111
|
-
// М
|
|
9564
|
+
// М м (visual approximation)
|
|
8112
9565
|
"\u041E": "O",
|
|
8113
9566
|
"\u043E": "o",
|
|
8114
9567
|
// О о
|
|
8115
9568
|
"\u0420": "P",
|
|
8116
9569
|
"\u0440": "p",
|
|
8117
9570
|
// Р р
|
|
9571
|
+
"\u0405": "S",
|
|
9572
|
+
"\u0455": "s",
|
|
9573
|
+
// Ѕ ѕ (Macedonian S)
|
|
8118
9574
|
"\u0422": "T",
|
|
8119
9575
|
"\u0442": "t",
|
|
8120
|
-
// Т
|
|
9576
|
+
// Т т (visual approximation)
|
|
8121
9577
|
"\u0425": "X",
|
|
8122
9578
|
"\u0445": "x",
|
|
8123
9579
|
// Х х
|
|
8124
9580
|
"\u0423": "Y",
|
|
8125
9581
|
"\u0443": "y",
|
|
8126
|
-
// У (
|
|
8127
|
-
|
|
9582
|
+
// У у (visual approximation)
|
|
9583
|
+
"\u0417": "3",
|
|
9584
|
+
// З (looks like 3)
|
|
9585
|
+
"\u04BB": "h",
|
|
9586
|
+
// һ (Shha)
|
|
9587
|
+
"\u04C0": "I",
|
|
9588
|
+
// Ӏ (Palochka)
|
|
9589
|
+
"\u04CF": "l",
|
|
9590
|
+
// ӏ (Palochka small)
|
|
9591
|
+
// ── Greek → Latin ─────────────────────────────────────────────────
|
|
8128
9592
|
"\u0391": "A",
|
|
8129
9593
|
"\u03B1": "a",
|
|
8130
|
-
// Α α (not exact)
|
|
9594
|
+
// Α α (alpha not exact)
|
|
8131
9595
|
"\u0392": "B",
|
|
8132
9596
|
"\u03B2": "b",
|
|
8133
9597
|
// Β β (not exact)
|
|
9598
|
+
"\u0393": "G",
|
|
9599
|
+
// Γ (visual approximation)
|
|
8134
9600
|
"\u0395": "E",
|
|
8135
9601
|
"\u03B5": "e",
|
|
8136
9602
|
// Ε ε (not exact)
|
|
9603
|
+
"\u0396": "Z",
|
|
9604
|
+
"\u03B6": "z",
|
|
9605
|
+
// Ζ ζ (not exact)
|
|
8137
9606
|
"\u0397": "H",
|
|
8138
|
-
|
|
9607
|
+
"\u03B7": "n",
|
|
9608
|
+
// Η η (not exact)
|
|
8139
9609
|
"\u0399": "I",
|
|
8140
9610
|
"\u03B9": "i",
|
|
8141
9611
|
// Ι ι
|
|
@@ -8159,8 +9629,78 @@ var InjectionDetector = class {
|
|
|
8159
9629
|
"\u03C5": "y",
|
|
8160
9630
|
// Υ υ (not exact)
|
|
8161
9631
|
"\u03A7": "X",
|
|
8162
|
-
"\u03C7": "x"
|
|
9632
|
+
"\u03C7": "x",
|
|
8163
9633
|
// Χ χ (not exact)
|
|
9634
|
+
"\u03C9": "w",
|
|
9635
|
+
// ω (omega, visual approximation)
|
|
9636
|
+
// ── Armenian → Latin ──────────────────────────────────────────────
|
|
9637
|
+
"\u0555": "O",
|
|
9638
|
+
// Օ
|
|
9639
|
+
"\u0585": "o",
|
|
9640
|
+
// օ
|
|
9641
|
+
"\u054D": "S",
|
|
9642
|
+
// Ս
|
|
9643
|
+
"\u057D": "s",
|
|
9644
|
+
// ս
|
|
9645
|
+
"\u054C": "L",
|
|
9646
|
+
// Լ (visual approximation)
|
|
9647
|
+
"\u0570": "h",
|
|
9648
|
+
// հ
|
|
9649
|
+
// ── Cherokee → Latin ──────────────────────────────────────────────
|
|
9650
|
+
"\u13A0": "D",
|
|
9651
|
+
// Ꭰ
|
|
9652
|
+
"\u13B3": "W",
|
|
9653
|
+
// Ꮃ
|
|
9654
|
+
"\u13A1": "R",
|
|
9655
|
+
// Ꭱ
|
|
9656
|
+
"\u13AA": "G",
|
|
9657
|
+
// Ꭺ (looks like A but maps to G sound)
|
|
9658
|
+
"\u13D2": "V",
|
|
9659
|
+
// Ꮢ (visual approximation)
|
|
9660
|
+
// ── Georgian → Latin ──────────────────────────────────────────────
|
|
9661
|
+
"\u10D5": "v",
|
|
9662
|
+
// ვ (Georgian letter vin)
|
|
9663
|
+
"\u10D3": "d",
|
|
9664
|
+
// დ (Georgian letter don)
|
|
9665
|
+
"\u10DA": "l",
|
|
9666
|
+
// ლ (Georgian letter las)
|
|
9667
|
+
// ── Latin special → Latin ────────────────────────────────────────
|
|
9668
|
+
"\u0131": "i",
|
|
9669
|
+
// ı (Latin small letter dotless i)
|
|
9670
|
+
// ── Symbols / Mathematical → Latin ────────────────────────────────
|
|
9671
|
+
// Note: NFKC normalization handles mathematical alphanumerics (U+1D400–U+1D7FF)
|
|
9672
|
+
"\u2160": "I",
|
|
9673
|
+
// Ⅰ (Roman numeral one)
|
|
9674
|
+
"\u2164": "V",
|
|
9675
|
+
// Ⅴ (Roman numeral five)
|
|
9676
|
+
"\u2169": "X",
|
|
9677
|
+
// Ⅹ (Roman numeral ten)
|
|
9678
|
+
"\u216C": "L",
|
|
9679
|
+
// Ⅼ (Roman numeral fifty)
|
|
9680
|
+
"\u216D": "C",
|
|
9681
|
+
// Ⅽ (Roman numeral one hundred)
|
|
9682
|
+
"\u216E": "D",
|
|
9683
|
+
// Ⅾ (Roman numeral five hundred)
|
|
9684
|
+
"\u216F": "M",
|
|
9685
|
+
// Ⅿ (Roman numeral one thousand)
|
|
9686
|
+
"\u2170": "i",
|
|
9687
|
+
// ⅰ (small Roman numeral one)
|
|
9688
|
+
"\u2174": "v",
|
|
9689
|
+
// ⅴ (small Roman numeral five)
|
|
9690
|
+
"\u2179": "x",
|
|
9691
|
+
// ⅹ (small Roman numeral ten)
|
|
9692
|
+
"\u217C": "l",
|
|
9693
|
+
// ⅼ (small Roman numeral fifty)
|
|
9694
|
+
"\u217D": "c",
|
|
9695
|
+
// ⅽ (small Roman numeral one hundred)
|
|
9696
|
+
"\u217E": "d",
|
|
9697
|
+
// ⅾ (small Roman numeral five hundred)
|
|
9698
|
+
"\u217F": "m",
|
|
9699
|
+
// ⅿ (small Roman numeral one thousand)
|
|
9700
|
+
"\u0251": "a",
|
|
9701
|
+
// ɑ (Latin alpha — looks like 'a')
|
|
9702
|
+
"\u0261": "g"
|
|
9703
|
+
// ɡ (Latin small letter script G)
|
|
8164
9704
|
};
|
|
8165
9705
|
let result = value;
|
|
8166
9706
|
if (/[^\x00-\x7F]/.test(value)) {
|
|
@@ -8250,6 +9790,7 @@ var ApprovalGate = class {
|
|
|
8250
9790
|
auditLog;
|
|
8251
9791
|
injectionDetector;
|
|
8252
9792
|
onInjectionAlert;
|
|
9793
|
+
proxyTierResolver;
|
|
8253
9794
|
constructor(policy, baseline, channel, auditLog, injectionDetector, onInjectionAlert) {
|
|
8254
9795
|
this.policy = policy;
|
|
8255
9796
|
this.baseline = baseline;
|
|
@@ -8258,6 +9799,12 @@ var ApprovalGate = class {
|
|
|
8258
9799
|
this.injectionDetector = injectionDetector ?? new InjectionDetector();
|
|
8259
9800
|
this.onInjectionAlert = onInjectionAlert;
|
|
8260
9801
|
}
|
|
9802
|
+
/**
|
|
9803
|
+
* Set the proxy tier resolver. Called after the proxy router is initialized.
|
|
9804
|
+
*/
|
|
9805
|
+
setProxyTierResolver(resolver) {
|
|
9806
|
+
this.proxyTierResolver = resolver;
|
|
9807
|
+
}
|
|
8261
9808
|
/**
|
|
8262
9809
|
* Evaluate a tool call against the Principal Policy.
|
|
8263
9810
|
*
|
|
@@ -8310,6 +9857,38 @@ var ApprovalGate = class {
|
|
|
8310
9857
|
);
|
|
8311
9858
|
}
|
|
8312
9859
|
}
|
|
9860
|
+
if (toolName.startsWith("proxy/") && this.proxyTierResolver) {
|
|
9861
|
+
const proxyTier = this.proxyTierResolver(toolName);
|
|
9862
|
+
if (proxyTier !== null) {
|
|
9863
|
+
if (proxyTier === 1) {
|
|
9864
|
+
return this.requestApproval(operation, 1, `Proxy tool "${toolName}" is configured as Tier 1 (always requires approval)`, {
|
|
9865
|
+
operation: toolName,
|
|
9866
|
+
proxy: true,
|
|
9867
|
+
args_summary: this.summarizeArgs(args)
|
|
9868
|
+
});
|
|
9869
|
+
}
|
|
9870
|
+
if (proxyTier === 2) {
|
|
9871
|
+
const anomaly2 = this.detectAnomaly(operation, args);
|
|
9872
|
+
if (anomaly2) {
|
|
9873
|
+
return this.requestApproval(operation, 2, `Proxy: ${anomaly2.reason}`, {
|
|
9874
|
+
...anomaly2.context,
|
|
9875
|
+
proxy: true
|
|
9876
|
+
});
|
|
9877
|
+
}
|
|
9878
|
+
}
|
|
9879
|
+
this.auditLog.append("l2", `gate_allow_proxy:${toolName}`, "system", {
|
|
9880
|
+
tier: proxyTier,
|
|
9881
|
+
operation: toolName,
|
|
9882
|
+
proxy: true
|
|
9883
|
+
});
|
|
9884
|
+
return {
|
|
9885
|
+
allowed: true,
|
|
9886
|
+
tier: proxyTier,
|
|
9887
|
+
reason: `Proxy operation allowed (Tier ${proxyTier})`,
|
|
9888
|
+
approval_required: false
|
|
9889
|
+
};
|
|
9890
|
+
}
|
|
9891
|
+
}
|
|
8313
9892
|
if (this.policy.tier1_always_approve.includes(operation)) {
|
|
8314
9893
|
return this.requestApproval(operation, 1, `"${operation}" is a Tier 1 operation (always requires approval)`, {
|
|
8315
9894
|
operation,
|
|
@@ -9987,7 +11566,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
|
|
|
9987
11566
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
9988
11567
|
const canonicalBytes = canonicalize(outcome);
|
|
9989
11568
|
const canonicalString = new TextDecoder().decode(canonicalBytes);
|
|
9990
|
-
const
|
|
11569
|
+
const sha2565 = createCommitment(canonicalString);
|
|
9991
11570
|
let pedersenData;
|
|
9992
11571
|
if (includePedersen && Number.isInteger(outcome.rounds) && outcome.rounds >= 0) {
|
|
9993
11572
|
const pedersen = createPedersenCommitment(outcome.rounds);
|
|
@@ -9999,7 +11578,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
|
|
|
9999
11578
|
const commitmentPayload = {
|
|
10000
11579
|
bridge_commitment_id: commitmentId,
|
|
10001
11580
|
session_id: outcome.session_id,
|
|
10002
|
-
sha256_commitment:
|
|
11581
|
+
sha256_commitment: sha2565.commitment,
|
|
10003
11582
|
terms_hash: outcome.terms_hash,
|
|
10004
11583
|
committer_did: identity.did,
|
|
10005
11584
|
committed_at: now,
|
|
@@ -10010,8 +11589,8 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
|
|
|
10010
11589
|
return {
|
|
10011
11590
|
bridge_commitment_id: commitmentId,
|
|
10012
11591
|
session_id: outcome.session_id,
|
|
10013
|
-
sha256_commitment:
|
|
10014
|
-
blinding_factor:
|
|
11592
|
+
sha256_commitment: sha2565.commitment,
|
|
11593
|
+
blinding_factor: sha2565.blinding_factor,
|
|
10015
11594
|
committer_did: identity.did,
|
|
10016
11595
|
signature: toBase64url(signature),
|
|
10017
11596
|
pedersen_commitment: pedersenData,
|
|
@@ -13087,7 +14666,8 @@ function createDefaultProfile() {
|
|
|
13087
14666
|
audit_logging: { enabled: true },
|
|
13088
14667
|
injection_detection: { enabled: true },
|
|
13089
14668
|
context_gating: { enabled: false },
|
|
13090
|
-
approval_gate: { enabled:
|
|
14669
|
+
approval_gate: { enabled: true },
|
|
14670
|
+
// SEC-057: always enabled — core enforcement
|
|
13091
14671
|
zk_proofs: { enabled: false }
|
|
13092
14672
|
},
|
|
13093
14673
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -13138,6 +14718,9 @@ var SovereigntyProfileStore = class {
|
|
|
13138
14718
|
if (!this.profile) {
|
|
13139
14719
|
await this.load();
|
|
13140
14720
|
}
|
|
14721
|
+
if (updates.approval_gate && updates.approval_gate.enabled === false) {
|
|
14722
|
+
throw new Error("approval_gate cannot be disabled \u2014 it is a core enforcement feature");
|
|
14723
|
+
}
|
|
13141
14724
|
const features = this.profile.features;
|
|
13142
14725
|
if (updates.audit_logging !== void 0) {
|
|
13143
14726
|
if (updates.audit_logging.enabled !== void 0) {
|
|
@@ -13192,6 +14775,48 @@ var SovereigntyProfileStore = class {
|
|
|
13192
14775
|
features.zk_proofs.enabled = updates.zk_proofs.enabled;
|
|
13193
14776
|
}
|
|
13194
14777
|
}
|
|
14778
|
+
if (updates.upstream_servers !== void 0) {
|
|
14779
|
+
if (!Array.isArray(updates.upstream_servers)) {
|
|
14780
|
+
throw new Error("upstream_servers must be an array");
|
|
14781
|
+
}
|
|
14782
|
+
for (const server of updates.upstream_servers) {
|
|
14783
|
+
if (!server.name || typeof server.name !== "string") {
|
|
14784
|
+
throw new Error("Each upstream server must have a name");
|
|
14785
|
+
}
|
|
14786
|
+
if (server.name.length > 128) {
|
|
14787
|
+
throw new Error("Upstream server name must be 128 characters or fewer");
|
|
14788
|
+
}
|
|
14789
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(server.name)) {
|
|
14790
|
+
throw new Error("Upstream server name must contain only alphanumeric characters, hyphens, and underscores");
|
|
14791
|
+
}
|
|
14792
|
+
if (!server.transport || typeof server.transport !== "object") {
|
|
14793
|
+
throw new Error("Each upstream server must have a transport configuration");
|
|
14794
|
+
}
|
|
14795
|
+
if (server.transport.type !== "stdio" && server.transport.type !== "sse") {
|
|
14796
|
+
throw new Error("Transport type must be 'stdio' or 'sse'");
|
|
14797
|
+
}
|
|
14798
|
+
if (server.transport.type === "stdio" && !server.transport.command) {
|
|
14799
|
+
throw new Error("stdio transport requires a command");
|
|
14800
|
+
}
|
|
14801
|
+
if (server.transport.type === "sse" && !server.transport.url) {
|
|
14802
|
+
throw new Error("sse transport requires a url");
|
|
14803
|
+
}
|
|
14804
|
+
if (typeof server.enabled !== "boolean") {
|
|
14805
|
+
throw new Error("Each upstream server must have enabled as a boolean");
|
|
14806
|
+
}
|
|
14807
|
+
if (![1, 2, 3].includes(server.default_tier)) {
|
|
14808
|
+
throw new Error("default_tier must be 1, 2, or 3");
|
|
14809
|
+
}
|
|
14810
|
+
if (server.tool_overrides) {
|
|
14811
|
+
for (const [, override] of Object.entries(server.tool_overrides)) {
|
|
14812
|
+
if (![1, 2, 3].includes(override.tier)) {
|
|
14813
|
+
throw new Error("tool_overrides tier must be 1, 2, or 3");
|
|
14814
|
+
}
|
|
14815
|
+
}
|
|
14816
|
+
}
|
|
14817
|
+
}
|
|
14818
|
+
this.profile.upstream_servers = updates.upstream_servers;
|
|
14819
|
+
}
|
|
13195
14820
|
this.profile.updated_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
13196
14821
|
await this.persist();
|
|
13197
14822
|
return this.profile;
|
|
@@ -13337,21 +14962,855 @@ function createSovereigntyProfileTools(profileStore, auditLog) {
|
|
|
13337
14962
|
];
|
|
13338
14963
|
return { tools };
|
|
13339
14964
|
}
|
|
13340
|
-
|
|
13341
|
-
|
|
13342
|
-
|
|
13343
|
-
|
|
13344
|
-
|
|
13345
|
-
|
|
13346
|
-
|
|
13347
|
-
|
|
13348
|
-
|
|
13349
|
-
|
|
13350
|
-
|
|
13351
|
-
|
|
13352
|
-
|
|
13353
|
-
|
|
13354
|
-
|
|
14965
|
+
var MAX_RETRIES = 5;
|
|
14966
|
+
var BASE_BACKOFF_MS = 1e3;
|
|
14967
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
14968
|
+
var MAX_UPSTREAM_SERVERS = 20;
|
|
14969
|
+
var ClientManager = class {
|
|
14970
|
+
connections = /* @__PURE__ */ new Map();
|
|
14971
|
+
onStateChange;
|
|
14972
|
+
shutdownRequested = false;
|
|
14973
|
+
constructor(options) {
|
|
14974
|
+
this.onStateChange = options?.onStateChange;
|
|
14975
|
+
}
|
|
14976
|
+
/**
|
|
14977
|
+
* Configure upstream servers. Disconnects removed servers, connects new ones.
|
|
14978
|
+
* Non-blocking — connection failures are handled asynchronously.
|
|
14979
|
+
*/
|
|
14980
|
+
async configure(servers) {
|
|
14981
|
+
if (servers.length > MAX_UPSTREAM_SERVERS) {
|
|
14982
|
+
throw new Error(`Maximum ${MAX_UPSTREAM_SERVERS} upstream servers allowed`);
|
|
14983
|
+
}
|
|
14984
|
+
const SAFE_SERVER_NAME = /^[a-zA-Z0-9_\-]+$/;
|
|
14985
|
+
const newNames = new Set(servers.filter((s) => {
|
|
14986
|
+
if (!SAFE_SERVER_NAME.test(s.name)) {
|
|
14987
|
+
return false;
|
|
14988
|
+
}
|
|
14989
|
+
return s.enabled;
|
|
14990
|
+
}).map((s) => s.name));
|
|
14991
|
+
for (const [name] of this.connections) {
|
|
14992
|
+
if (!newNames.has(name)) {
|
|
14993
|
+
await this.disconnectServer(name);
|
|
14994
|
+
}
|
|
14995
|
+
}
|
|
14996
|
+
for (const server of servers) {
|
|
14997
|
+
if (!SAFE_SERVER_NAME.test(server.name)) {
|
|
14998
|
+
continue;
|
|
14999
|
+
}
|
|
15000
|
+
if (!server.enabled) {
|
|
15001
|
+
if (this.connections.has(server.name)) {
|
|
15002
|
+
await this.disconnectServer(server.name);
|
|
15003
|
+
}
|
|
15004
|
+
continue;
|
|
15005
|
+
}
|
|
15006
|
+
const existing = this.connections.get(server.name);
|
|
15007
|
+
if (existing && existing.state === "connected") {
|
|
15008
|
+
existing.server = server;
|
|
15009
|
+
continue;
|
|
15010
|
+
}
|
|
15011
|
+
this.connectServer(server);
|
|
15012
|
+
}
|
|
15013
|
+
}
|
|
15014
|
+
/**
|
|
15015
|
+
* Get all discovered tools across all connected upstream servers.
|
|
15016
|
+
*/
|
|
15017
|
+
getAllTools() {
|
|
15018
|
+
const result = /* @__PURE__ */ new Map();
|
|
15019
|
+
for (const [name, conn] of this.connections) {
|
|
15020
|
+
if (conn.state === "connected" && conn.tools.length > 0) {
|
|
15021
|
+
result.set(name, conn.tools);
|
|
15022
|
+
}
|
|
15023
|
+
}
|
|
15024
|
+
return result;
|
|
15025
|
+
}
|
|
15026
|
+
/**
|
|
15027
|
+
* Get connection status for all configured servers.
|
|
15028
|
+
*/
|
|
15029
|
+
getStatus() {
|
|
15030
|
+
return Array.from(this.connections.values()).map((conn) => ({
|
|
15031
|
+
name: conn.server.name,
|
|
15032
|
+
state: conn.state,
|
|
15033
|
+
transport_type: conn.server.transport.type,
|
|
15034
|
+
tool_count: conn.tools.length,
|
|
15035
|
+
error: conn.error
|
|
15036
|
+
}));
|
|
15037
|
+
}
|
|
15038
|
+
/**
|
|
15039
|
+
* Get the upstream server config by name.
|
|
15040
|
+
*/
|
|
15041
|
+
getServerConfig(name) {
|
|
15042
|
+
return this.connections.get(name)?.server;
|
|
15043
|
+
}
|
|
15044
|
+
/**
|
|
15045
|
+
* Call a tool on an upstream server.
|
|
15046
|
+
*/
|
|
15047
|
+
async callTool(serverName, toolName, args) {
|
|
15048
|
+
const conn = this.connections.get(serverName);
|
|
15049
|
+
if (!conn) {
|
|
15050
|
+
throw new Error(`Upstream server "${serverName}" is not configured`);
|
|
15051
|
+
}
|
|
15052
|
+
if (conn.state !== "connected" || !conn.client) {
|
|
15053
|
+
throw new Error(`Upstream server "${serverName}" is not connected (state: ${conn.state})`);
|
|
15054
|
+
}
|
|
15055
|
+
const result = await conn.client.callTool({
|
|
15056
|
+
name: toolName,
|
|
15057
|
+
arguments: args
|
|
15058
|
+
});
|
|
15059
|
+
return result;
|
|
15060
|
+
}
|
|
15061
|
+
/**
|
|
15062
|
+
* Shut down all connections cleanly.
|
|
15063
|
+
*/
|
|
15064
|
+
async shutdown() {
|
|
15065
|
+
this.shutdownRequested = true;
|
|
15066
|
+
for (const conn of this.connections.values()) {
|
|
15067
|
+
if (conn.retryTimer) {
|
|
15068
|
+
clearTimeout(conn.retryTimer);
|
|
15069
|
+
conn.retryTimer = void 0;
|
|
15070
|
+
}
|
|
15071
|
+
}
|
|
15072
|
+
const disconnects = Array.from(this.connections.keys()).map(
|
|
15073
|
+
(name) => this.disconnectServer(name)
|
|
15074
|
+
);
|
|
15075
|
+
await Promise.allSettled(disconnects);
|
|
15076
|
+
}
|
|
15077
|
+
// ── Private ───────────────────────────────────────────────────────────
|
|
15078
|
+
/**
|
|
15079
|
+
* Connect to an upstream server (non-blocking).
|
|
15080
|
+
* Spawns connection attempt in background — does not throw.
|
|
15081
|
+
*/
|
|
15082
|
+
connectServer(server) {
|
|
15083
|
+
const conn = {
|
|
15084
|
+
server,
|
|
15085
|
+
client: null,
|
|
15086
|
+
transport: null,
|
|
15087
|
+
state: "connecting",
|
|
15088
|
+
tools: [],
|
|
15089
|
+
retryCount: 0
|
|
15090
|
+
};
|
|
15091
|
+
this.connections.set(server.name, conn);
|
|
15092
|
+
this.notifyStateChange(conn);
|
|
15093
|
+
this.doConnect(conn).catch(() => {
|
|
15094
|
+
});
|
|
15095
|
+
}
|
|
15096
|
+
/**
|
|
15097
|
+
* Perform the actual connection to an upstream server.
|
|
15098
|
+
*/
|
|
15099
|
+
async doConnect(conn) {
|
|
15100
|
+
try {
|
|
15101
|
+
conn.state = "connecting";
|
|
15102
|
+
this.notifyStateChange(conn);
|
|
15103
|
+
let transport;
|
|
15104
|
+
if (conn.server.transport.type === "stdio") {
|
|
15105
|
+
if (!conn.server.transport.command) {
|
|
15106
|
+
throw new Error("stdio transport requires a command");
|
|
15107
|
+
}
|
|
15108
|
+
if (conn.server.transport.args) {
|
|
15109
|
+
const SAFE_ARG_PATTERN = /^[a-zA-Z0-9._\-\/=:@]+$/;
|
|
15110
|
+
for (const arg of conn.server.transport.args) {
|
|
15111
|
+
if (!SAFE_ARG_PATTERN.test(arg)) {
|
|
15112
|
+
throw new Error(`Unsafe argument rejected: contains disallowed characters`);
|
|
15113
|
+
}
|
|
15114
|
+
}
|
|
15115
|
+
}
|
|
15116
|
+
const ENV_BLOCKLIST = /* @__PURE__ */ new Set([
|
|
15117
|
+
"PATH",
|
|
15118
|
+
"HOME",
|
|
15119
|
+
"USER",
|
|
15120
|
+
"SHELL",
|
|
15121
|
+
"NODE_OPTIONS",
|
|
15122
|
+
"NODE_PATH",
|
|
15123
|
+
"LD_PRELOAD",
|
|
15124
|
+
"LD_LIBRARY_PATH",
|
|
15125
|
+
"DYLD_INSERT_LIBRARIES",
|
|
15126
|
+
"PYTHONPATH",
|
|
15127
|
+
"RUBYLIB",
|
|
15128
|
+
"PERL5LIB",
|
|
15129
|
+
"HTTP_PROXY",
|
|
15130
|
+
"HTTPS_PROXY",
|
|
15131
|
+
"NO_PROXY",
|
|
15132
|
+
"http_proxy",
|
|
15133
|
+
"https_proxy",
|
|
15134
|
+
"no_proxy"
|
|
15135
|
+
]);
|
|
15136
|
+
let transportEnv;
|
|
15137
|
+
if (conn.server.transport.env) {
|
|
15138
|
+
const safeEnv = { ...process.env };
|
|
15139
|
+
for (const [key, value] of Object.entries(conn.server.transport.env)) {
|
|
15140
|
+
if (!ENV_BLOCKLIST.has(key)) {
|
|
15141
|
+
safeEnv[key] = value;
|
|
15142
|
+
}
|
|
15143
|
+
}
|
|
15144
|
+
transportEnv = safeEnv;
|
|
15145
|
+
}
|
|
15146
|
+
transport = new StdioClientTransport({
|
|
15147
|
+
command: conn.server.transport.command,
|
|
15148
|
+
args: conn.server.transport.args,
|
|
15149
|
+
env: transportEnv
|
|
15150
|
+
});
|
|
15151
|
+
} else {
|
|
15152
|
+
if (!conn.server.transport.url) {
|
|
15153
|
+
throw new Error("sse transport requires a url");
|
|
15154
|
+
}
|
|
15155
|
+
const ssrfUrl = new URL(conn.server.transport.url);
|
|
15156
|
+
if (ssrfUrl.protocol !== "http:" && ssrfUrl.protocol !== "https:") {
|
|
15157
|
+
throw new Error("SSE transport URL must use http or https scheme");
|
|
15158
|
+
}
|
|
15159
|
+
transport = new SSEClientTransport(ssrfUrl);
|
|
15160
|
+
}
|
|
15161
|
+
const client = new Client(
|
|
15162
|
+
{ name: `sanctuary-proxy/${conn.server.name}`, version: "1.0.0" },
|
|
15163
|
+
{ capabilities: {} }
|
|
15164
|
+
);
|
|
15165
|
+
await client.connect(transport);
|
|
15166
|
+
conn.client = client;
|
|
15167
|
+
conn.transport = transport;
|
|
15168
|
+
conn.state = "connected";
|
|
15169
|
+
conn.error = void 0;
|
|
15170
|
+
conn.retryCount = 0;
|
|
15171
|
+
await this.discoverTools(conn);
|
|
15172
|
+
this.notifyStateChange(conn);
|
|
15173
|
+
} catch (err) {
|
|
15174
|
+
const message = err instanceof Error ? err.message : "Unknown connection error";
|
|
15175
|
+
conn.state = "error";
|
|
15176
|
+
conn.error = message;
|
|
15177
|
+
conn.client = null;
|
|
15178
|
+
conn.transport = null;
|
|
15179
|
+
this.notifyStateChange(conn);
|
|
15180
|
+
this.scheduleRetry(conn);
|
|
15181
|
+
}
|
|
15182
|
+
}
|
|
15183
|
+
/**
|
|
15184
|
+
* Discover tools from a connected upstream server.
|
|
15185
|
+
*/
|
|
15186
|
+
async discoverTools(conn) {
|
|
15187
|
+
if (!conn.client || conn.state !== "connected") return;
|
|
15188
|
+
try {
|
|
15189
|
+
const result = await conn.client.listTools();
|
|
15190
|
+
conn.tools = (result.tools ?? []).map((t) => ({
|
|
15191
|
+
name: t.name,
|
|
15192
|
+
description: t.description ?? "",
|
|
15193
|
+
inputSchema: t.inputSchema ?? { type: "object", properties: {} }
|
|
15194
|
+
}));
|
|
15195
|
+
} catch {
|
|
15196
|
+
conn.tools = [];
|
|
15197
|
+
}
|
|
15198
|
+
}
|
|
15199
|
+
/**
|
|
15200
|
+
* Schedule a reconnection attempt with exponential backoff.
|
|
15201
|
+
*/
|
|
15202
|
+
scheduleRetry(conn) {
|
|
15203
|
+
if (this.shutdownRequested) return;
|
|
15204
|
+
if (conn.retryCount >= MAX_RETRIES) {
|
|
15205
|
+
conn.error = `Max retries (${MAX_RETRIES}) exceeded. Last error: ${conn.error}`;
|
|
15206
|
+
this.notifyStateChange(conn);
|
|
15207
|
+
return;
|
|
15208
|
+
}
|
|
15209
|
+
const delay = Math.min(
|
|
15210
|
+
BASE_BACKOFF_MS * Math.pow(2, conn.retryCount),
|
|
15211
|
+
MAX_BACKOFF_MS
|
|
15212
|
+
);
|
|
15213
|
+
conn.retryCount++;
|
|
15214
|
+
conn.retryTimer = setTimeout(() => {
|
|
15215
|
+
if (this.shutdownRequested) return;
|
|
15216
|
+
conn.retryTimer = void 0;
|
|
15217
|
+
this.doConnect(conn).catch(() => {
|
|
15218
|
+
});
|
|
15219
|
+
}, delay);
|
|
15220
|
+
}
|
|
15221
|
+
/**
|
|
15222
|
+
* Disconnect a specific upstream server.
|
|
15223
|
+
*/
|
|
15224
|
+
async disconnectServer(name) {
|
|
15225
|
+
const conn = this.connections.get(name);
|
|
15226
|
+
if (!conn) return;
|
|
15227
|
+
if (conn.retryTimer) {
|
|
15228
|
+
clearTimeout(conn.retryTimer);
|
|
15229
|
+
conn.retryTimer = void 0;
|
|
15230
|
+
}
|
|
15231
|
+
if (conn.client) {
|
|
15232
|
+
try {
|
|
15233
|
+
await conn.client.close();
|
|
15234
|
+
} catch {
|
|
15235
|
+
}
|
|
15236
|
+
}
|
|
15237
|
+
if (conn.transport) {
|
|
15238
|
+
try {
|
|
15239
|
+
await conn.transport.close();
|
|
15240
|
+
} catch {
|
|
15241
|
+
}
|
|
15242
|
+
}
|
|
15243
|
+
this.connections.delete(name);
|
|
15244
|
+
}
|
|
15245
|
+
/**
|
|
15246
|
+
* Notify listener of state change.
|
|
15247
|
+
*/
|
|
15248
|
+
notifyStateChange(conn) {
|
|
15249
|
+
if (this.onStateChange) {
|
|
15250
|
+
try {
|
|
15251
|
+
this.onStateChange(conn.server.name, conn.state, conn.tools.length, conn.error);
|
|
15252
|
+
} catch {
|
|
15253
|
+
}
|
|
15254
|
+
}
|
|
15255
|
+
}
|
|
15256
|
+
};
|
|
15257
|
+
|
|
15258
|
+
// src/proxy/proxy-router.ts
|
|
15259
|
+
var UPSTREAM_CALL_TIMEOUT_MS = 3e4;
|
|
15260
|
+
var ProxyRouter = class {
|
|
15261
|
+
clientManager;
|
|
15262
|
+
injectionDetector;
|
|
15263
|
+
auditLog;
|
|
15264
|
+
options;
|
|
15265
|
+
constructor(clientManager, injectionDetector, auditLog, options) {
|
|
15266
|
+
this.clientManager = clientManager;
|
|
15267
|
+
this.injectionDetector = injectionDetector;
|
|
15268
|
+
this.auditLog = auditLog;
|
|
15269
|
+
this.options = options ?? {};
|
|
15270
|
+
}
|
|
15271
|
+
/**
|
|
15272
|
+
* Convert all discovered upstream tools to Sanctuary ToolDefinitions.
|
|
15273
|
+
* Each tool is registered as `proxy/{server_name}/{tool_name}`.
|
|
15274
|
+
*/
|
|
15275
|
+
getProxiedTools() {
|
|
15276
|
+
const tools = [];
|
|
15277
|
+
const allUpstreamTools = this.clientManager.getAllTools();
|
|
15278
|
+
for (const [serverName, serverTools] of allUpstreamTools) {
|
|
15279
|
+
for (const upstreamTool of serverTools) {
|
|
15280
|
+
const proxyName = `proxy/${serverName}/${upstreamTool.name}`;
|
|
15281
|
+
tools.push({
|
|
15282
|
+
name: proxyName,
|
|
15283
|
+
description: `[via ${serverName}] ${upstreamTool.description}`,
|
|
15284
|
+
inputSchema: upstreamTool.inputSchema,
|
|
15285
|
+
handler: this.createHandler(serverName, upstreamTool.name)
|
|
15286
|
+
});
|
|
15287
|
+
}
|
|
15288
|
+
}
|
|
15289
|
+
return tools;
|
|
15290
|
+
}
|
|
15291
|
+
/**
|
|
15292
|
+
* Determine the tier for a proxied tool call.
|
|
15293
|
+
* Checks tool_overrides first, then falls back to default_tier.
|
|
15294
|
+
*/
|
|
15295
|
+
getTierForTool(serverName, toolName) {
|
|
15296
|
+
const serverConfig = this.clientManager.getServerConfig(serverName);
|
|
15297
|
+
if (!serverConfig) return 2;
|
|
15298
|
+
if (serverConfig.tool_overrides?.[toolName]) {
|
|
15299
|
+
return serverConfig.tool_overrides[toolName].tier;
|
|
15300
|
+
}
|
|
15301
|
+
return serverConfig.default_tier;
|
|
15302
|
+
}
|
|
15303
|
+
/**
|
|
15304
|
+
* Parse a proxy tool name into server name and tool name.
|
|
15305
|
+
* Returns null if the name doesn't match the proxy namespace.
|
|
15306
|
+
*/
|
|
15307
|
+
static parseProxyToolName(fullName) {
|
|
15308
|
+
if (!fullName.startsWith("proxy/")) return null;
|
|
15309
|
+
const rest = fullName.slice("proxy/".length);
|
|
15310
|
+
const slashIdx = rest.indexOf("/");
|
|
15311
|
+
if (slashIdx === -1) return null;
|
|
15312
|
+
return {
|
|
15313
|
+
serverName: rest.slice(0, slashIdx),
|
|
15314
|
+
toolName: rest.slice(slashIdx + 1)
|
|
15315
|
+
};
|
|
15316
|
+
}
|
|
15317
|
+
// ── Private ───────────────────────────────────────────────────────────
|
|
15318
|
+
/**
|
|
15319
|
+
* Create a handler for a specific proxied tool.
|
|
15320
|
+
* The handler runs the full enforcement chain before forwarding.
|
|
15321
|
+
*/
|
|
15322
|
+
createHandler(serverName, toolName) {
|
|
15323
|
+
return async (args) => {
|
|
15324
|
+
const proxyName = `proxy/${serverName}/${toolName}`;
|
|
15325
|
+
const start = Date.now();
|
|
15326
|
+
const tier = this.getTierForTool(serverName, toolName);
|
|
15327
|
+
try {
|
|
15328
|
+
const injectionResult = this.injectionDetector.scan(proxyName, args);
|
|
15329
|
+
if (injectionResult.flagged && injectionResult.recommendation === "block") {
|
|
15330
|
+
this.auditLog.append("l2", `proxy_injection_blocked:${proxyName}`, "system", {
|
|
15331
|
+
server: serverName,
|
|
15332
|
+
tool: toolName,
|
|
15333
|
+
tier,
|
|
15334
|
+
confidence: injectionResult.confidence,
|
|
15335
|
+
latency_ms: Date.now() - start
|
|
15336
|
+
}, "failure");
|
|
15337
|
+
return toolResult({
|
|
15338
|
+
error: "Operation not permitted",
|
|
15339
|
+
proxy: true
|
|
15340
|
+
});
|
|
15341
|
+
}
|
|
15342
|
+
if (injectionResult.flagged && injectionResult.recommendation === "escalate") {
|
|
15343
|
+
this.auditLog.append("l2", `proxy_injection_escalated:${proxyName}`, "system", {
|
|
15344
|
+
server: serverName,
|
|
15345
|
+
tool: toolName,
|
|
15346
|
+
tier,
|
|
15347
|
+
confidence: injectionResult.confidence
|
|
15348
|
+
});
|
|
15349
|
+
}
|
|
15350
|
+
let filteredArgs = args;
|
|
15351
|
+
if (this.options.contextGateFilter) {
|
|
15352
|
+
try {
|
|
15353
|
+
filteredArgs = await this.options.contextGateFilter(proxyName, args);
|
|
15354
|
+
} catch {
|
|
15355
|
+
}
|
|
15356
|
+
}
|
|
15357
|
+
if (this.options.governor) {
|
|
15358
|
+
const govResult = this.options.governor.check(serverName, toolName, filteredArgs);
|
|
15359
|
+
if (!govResult.allowed) {
|
|
15360
|
+
this.auditLog.append("l2", `proxy_governor_blocked:${proxyName}`, "system", {
|
|
15361
|
+
server: serverName,
|
|
15362
|
+
tool: toolName,
|
|
15363
|
+
tier,
|
|
15364
|
+
reason: govResult.reason,
|
|
15365
|
+
latency_ms: Date.now() - start
|
|
15366
|
+
}, "failure");
|
|
15367
|
+
return toolResult({
|
|
15368
|
+
error: "Operation not permitted",
|
|
15369
|
+
proxy: true,
|
|
15370
|
+
governor_reason: govResult.reason
|
|
15371
|
+
});
|
|
15372
|
+
}
|
|
15373
|
+
if (govResult.reason === "duplicate_cached" && govResult.cached_result !== void 0) {
|
|
15374
|
+
this.auditLog.append("l2", `proxy_governor_cached:${proxyName}`, "system", {
|
|
15375
|
+
server: serverName,
|
|
15376
|
+
tool: toolName,
|
|
15377
|
+
tier,
|
|
15378
|
+
cached: true,
|
|
15379
|
+
latency_ms: Date.now() - start
|
|
15380
|
+
});
|
|
15381
|
+
return toolResult(govResult.cached_result ?? {});
|
|
15382
|
+
}
|
|
15383
|
+
}
|
|
15384
|
+
const result = await this.callWithTimeout(
|
|
15385
|
+
serverName,
|
|
15386
|
+
toolName,
|
|
15387
|
+
filteredArgs,
|
|
15388
|
+
UPSTREAM_CALL_TIMEOUT_MS
|
|
15389
|
+
);
|
|
15390
|
+
const latencyMs = Date.now() - start;
|
|
15391
|
+
if (this.options.governor) {
|
|
15392
|
+
this.options.governor.recordResult(serverName, toolName, filteredArgs, result);
|
|
15393
|
+
}
|
|
15394
|
+
this.auditLog.append("l2", `proxy_call:${proxyName}`, "system", {
|
|
15395
|
+
server: serverName,
|
|
15396
|
+
tool: toolName,
|
|
15397
|
+
tier,
|
|
15398
|
+
decision: "allowed",
|
|
15399
|
+
latency_ms: latencyMs
|
|
15400
|
+
});
|
|
15401
|
+
return this.normalizeResponse(result);
|
|
15402
|
+
} catch (err) {
|
|
15403
|
+
const latencyMs = Date.now() - start;
|
|
15404
|
+
const rawErrorMessage = err instanceof Error ? err.message : "Unknown upstream error";
|
|
15405
|
+
const sanitizeError = (msg) => {
|
|
15406
|
+
let safe = msg.substring(0, 200);
|
|
15407
|
+
safe = safe.replace(/\/[^\s]+/g, "[path-redacted]");
|
|
15408
|
+
safe = safe.replace(/(?:mongodb|postgres|mysql|redis):\/\/[^\s]+/g, "[connection-redacted]");
|
|
15409
|
+
return safe;
|
|
15410
|
+
};
|
|
15411
|
+
const errorMessage = sanitizeError(rawErrorMessage);
|
|
15412
|
+
this.auditLog.append("l2", `proxy_call:${proxyName}`, "system", {
|
|
15413
|
+
server: serverName,
|
|
15414
|
+
tool: toolName,
|
|
15415
|
+
tier,
|
|
15416
|
+
decision: "error",
|
|
15417
|
+
error: errorMessage,
|
|
15418
|
+
latency_ms: latencyMs
|
|
15419
|
+
}, "failure");
|
|
15420
|
+
return {
|
|
15421
|
+
content: [{
|
|
15422
|
+
type: "text",
|
|
15423
|
+
text: JSON.stringify({
|
|
15424
|
+
error: errorMessage,
|
|
15425
|
+
proxy: true,
|
|
15426
|
+
server: serverName,
|
|
15427
|
+
tool: toolName
|
|
15428
|
+
})
|
|
15429
|
+
}]
|
|
15430
|
+
};
|
|
15431
|
+
}
|
|
15432
|
+
};
|
|
15433
|
+
}
|
|
15434
|
+
/**
|
|
15435
|
+
* Call an upstream tool with a timeout.
|
|
15436
|
+
*/
|
|
15437
|
+
async callWithTimeout(serverName, toolName, args, timeoutMs) {
|
|
15438
|
+
return new Promise((resolve, reject) => {
|
|
15439
|
+
const timer = setTimeout(() => {
|
|
15440
|
+
reject(new Error(`Upstream tool call timed out after ${timeoutMs}ms`));
|
|
15441
|
+
}, timeoutMs);
|
|
15442
|
+
this.clientManager.callTool(serverName, toolName, args).then((result) => {
|
|
15443
|
+
clearTimeout(timer);
|
|
15444
|
+
resolve(result);
|
|
15445
|
+
}).catch((err) => {
|
|
15446
|
+
clearTimeout(timer);
|
|
15447
|
+
reject(err);
|
|
15448
|
+
});
|
|
15449
|
+
});
|
|
15450
|
+
}
|
|
15451
|
+
/**
|
|
15452
|
+
* Normalize an upstream response to the standard Sanctuary response format.
|
|
15453
|
+
*/
|
|
15454
|
+
normalizeResponse(result) {
|
|
15455
|
+
const MAX_RESPONSE_SIZE = 1e6;
|
|
15456
|
+
const MAX_TEXT_BLOCK_SIZE = 1e5;
|
|
15457
|
+
const responseStr = JSON.stringify(result);
|
|
15458
|
+
if (responseStr.length > MAX_RESPONSE_SIZE) {
|
|
15459
|
+
return toolResult({
|
|
15460
|
+
error: "upstream_response_too_large",
|
|
15461
|
+
max_bytes: MAX_RESPONSE_SIZE
|
|
15462
|
+
});
|
|
15463
|
+
}
|
|
15464
|
+
if (!result.content || !Array.isArray(result.content)) {
|
|
15465
|
+
return toolResult({ upstream_response: result });
|
|
15466
|
+
}
|
|
15467
|
+
const textContent = result.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => {
|
|
15468
|
+
const text = c.text;
|
|
15469
|
+
if (text.length > MAX_TEXT_BLOCK_SIZE) {
|
|
15470
|
+
return {
|
|
15471
|
+
type: "text",
|
|
15472
|
+
text: text.substring(0, MAX_TEXT_BLOCK_SIZE) + "\n[response truncated]"
|
|
15473
|
+
};
|
|
15474
|
+
}
|
|
15475
|
+
return { type: "text", text };
|
|
15476
|
+
});
|
|
15477
|
+
if (textContent.length > 0) {
|
|
15478
|
+
return { content: textContent };
|
|
15479
|
+
}
|
|
15480
|
+
return toolResult({ upstream_response: result.content });
|
|
15481
|
+
}
|
|
15482
|
+
};
|
|
15483
|
+
function strToBytes(s) {
|
|
15484
|
+
return new TextEncoder().encode(s);
|
|
15485
|
+
}
|
|
15486
|
+
function bytesToHex(bytes) {
|
|
15487
|
+
let hex = "";
|
|
15488
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
15489
|
+
hex += bytes[i].toString(16).padStart(2, "0");
|
|
15490
|
+
}
|
|
15491
|
+
return hex;
|
|
15492
|
+
}
|
|
15493
|
+
function sha256Hex(input) {
|
|
15494
|
+
return bytesToHex(sha256(strToBytes(input)));
|
|
15495
|
+
}
|
|
15496
|
+
var DEFAULT_CONFIG = {
|
|
15497
|
+
volume_limit: 200,
|
|
15498
|
+
volume_window_ms: 6e5,
|
|
15499
|
+
// 10 minutes
|
|
15500
|
+
rate_limit: 20,
|
|
15501
|
+
rate_window_ms: 6e4,
|
|
15502
|
+
// 1 minute
|
|
15503
|
+
duplicate_ttl_ms: 6e4,
|
|
15504
|
+
// 1 minute
|
|
15505
|
+
lifetime_limit: 1e3
|
|
15506
|
+
};
|
|
15507
|
+
var CallGovernor = class {
|
|
15508
|
+
config;
|
|
15509
|
+
/** Sliding window of all call timestamps for volume tracking */
|
|
15510
|
+
volumeWindow = [];
|
|
15511
|
+
/** Per-tool sliding window of call timestamps for rate tracking */
|
|
15512
|
+
rateWindows = /* @__PURE__ */ new Map();
|
|
15513
|
+
/** Duplicate cache: SHA-256(server+tool+args) -> cached result + expiry */
|
|
15514
|
+
duplicateCache = /* @__PURE__ */ new Map();
|
|
15515
|
+
/** Total calls this session */
|
|
15516
|
+
lifetimeCount = 0;
|
|
15517
|
+
/** Hard stop flag — set when lifetime limit is reached */
|
|
15518
|
+
hardStopped = false;
|
|
15519
|
+
constructor(config) {
|
|
15520
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
15521
|
+
}
|
|
15522
|
+
/**
|
|
15523
|
+
* Check if a call is allowed and apply governance.
|
|
15524
|
+
*
|
|
15525
|
+
* Evaluation order:
|
|
15526
|
+
* 1. Lifetime limit (hard stop — not recoverable without reset)
|
|
15527
|
+
* 2. Volume limit (sliding window)
|
|
15528
|
+
* 3. Rate limit per tool (escalates to Tier 2)
|
|
15529
|
+
* 4. Duplicate detection (returns cached result)
|
|
15530
|
+
*/
|
|
15531
|
+
check(serverName, toolName, args) {
|
|
15532
|
+
const now = Date.now();
|
|
15533
|
+
const effectiveConfig = this.getEffectiveConfig(serverName);
|
|
15534
|
+
if (this.hardStopped) {
|
|
15535
|
+
return {
|
|
15536
|
+
allowed: false,
|
|
15537
|
+
reason: "lifetime_exceeded"
|
|
15538
|
+
};
|
|
15539
|
+
}
|
|
15540
|
+
if (this.lifetimeCount >= effectiveConfig.lifetime_limit) {
|
|
15541
|
+
this.hardStopped = true;
|
|
15542
|
+
return {
|
|
15543
|
+
allowed: false,
|
|
15544
|
+
reason: "lifetime_exceeded"
|
|
15545
|
+
};
|
|
15546
|
+
}
|
|
15547
|
+
this.pruneVolumeWindow(now, effectiveConfig.volume_window_ms);
|
|
15548
|
+
if (this.volumeWindow.length >= effectiveConfig.volume_limit) {
|
|
15549
|
+
return {
|
|
15550
|
+
allowed: false,
|
|
15551
|
+
reason: "volume_exceeded"
|
|
15552
|
+
};
|
|
15553
|
+
}
|
|
15554
|
+
const toolKey = `${serverName}::${toolName}`;
|
|
15555
|
+
this.pruneRateWindow(toolKey, now, effectiveConfig.rate_window_ms);
|
|
15556
|
+
const rateWindow = this.rateWindows.get(toolKey);
|
|
15557
|
+
const currentRate = rateWindow ? rateWindow.length : 0;
|
|
15558
|
+
if (currentRate >= effectiveConfig.rate_limit) {
|
|
15559
|
+
return {
|
|
15560
|
+
allowed: false,
|
|
15561
|
+
reason: "rate_exceeded",
|
|
15562
|
+
escalate: true
|
|
15563
|
+
};
|
|
15564
|
+
}
|
|
15565
|
+
const callHash = this.computeCallHash(serverName, toolName, args);
|
|
15566
|
+
this.pruneDuplicateCache(now);
|
|
15567
|
+
const cached = this.duplicateCache.get(callHash);
|
|
15568
|
+
if (cached && cached.expires_at > now) {
|
|
15569
|
+
return {
|
|
15570
|
+
allowed: true,
|
|
15571
|
+
reason: "duplicate_cached",
|
|
15572
|
+
cached_result: cached.result
|
|
15573
|
+
};
|
|
15574
|
+
}
|
|
15575
|
+
this.volumeWindow.push(now);
|
|
15576
|
+
if (!this.rateWindows.has(toolKey)) {
|
|
15577
|
+
this.rateWindows.set(toolKey, []);
|
|
15578
|
+
}
|
|
15579
|
+
this.rateWindows.get(toolKey).push(now);
|
|
15580
|
+
this.lifetimeCount++;
|
|
15581
|
+
return { allowed: true };
|
|
15582
|
+
}
|
|
15583
|
+
/**
|
|
15584
|
+
* Record a successful call result for duplicate caching.
|
|
15585
|
+
*/
|
|
15586
|
+
recordResult(serverName, toolName, args, result) {
|
|
15587
|
+
const callHash = this.computeCallHash(serverName, toolName, args);
|
|
15588
|
+
const effectiveConfig = this.getEffectiveConfig(serverName);
|
|
15589
|
+
this.duplicateCache.set(callHash, {
|
|
15590
|
+
result,
|
|
15591
|
+
expires_at: Date.now() + effectiveConfig.duplicate_ttl_ms
|
|
15592
|
+
});
|
|
15593
|
+
}
|
|
15594
|
+
/**
|
|
15595
|
+
* Get current governor status for dashboard display.
|
|
15596
|
+
*/
|
|
15597
|
+
getStatus() {
|
|
15598
|
+
const now = Date.now();
|
|
15599
|
+
this.pruneVolumeWindow(now, this.config.volume_window_ms);
|
|
15600
|
+
this.pruneDuplicateCache(now);
|
|
15601
|
+
const rateByTool = {};
|
|
15602
|
+
for (const [toolKey, timestamps] of this.rateWindows.entries()) {
|
|
15603
|
+
const cutoff = now - this.config.rate_window_ms;
|
|
15604
|
+
const activeCount = timestamps.filter((t) => t >= cutoff).length;
|
|
15605
|
+
if (activeCount > 0) {
|
|
15606
|
+
rateByTool[toolKey] = activeCount;
|
|
15607
|
+
}
|
|
15608
|
+
}
|
|
15609
|
+
return {
|
|
15610
|
+
volume_current: this.volumeWindow.length,
|
|
15611
|
+
volume_limit: this.config.volume_limit,
|
|
15612
|
+
lifetime_current: this.lifetimeCount,
|
|
15613
|
+
lifetime_limit: this.config.lifetime_limit,
|
|
15614
|
+
rate_by_tool: rateByTool,
|
|
15615
|
+
duplicate_cache_size: this.duplicateCache.size,
|
|
15616
|
+
hard_stopped: this.hardStopped
|
|
15617
|
+
};
|
|
15618
|
+
}
|
|
15619
|
+
/**
|
|
15620
|
+
* Reset all counters (Tier 1 — requires approval).
|
|
15621
|
+
* Clears volume window, rate windows, duplicate cache,
|
|
15622
|
+
* lifetime counter, and hard stop flag.
|
|
15623
|
+
*/
|
|
15624
|
+
reset() {
|
|
15625
|
+
this.volumeWindow = [];
|
|
15626
|
+
this.rateWindows.clear();
|
|
15627
|
+
this.duplicateCache.clear();
|
|
15628
|
+
this.lifetimeCount = 0;
|
|
15629
|
+
this.hardStopped = false;
|
|
15630
|
+
}
|
|
15631
|
+
/**
|
|
15632
|
+
* Get the effective config for a given server, merging per-server overrides.
|
|
15633
|
+
*/
|
|
15634
|
+
getEffectiveConfig(serverName) {
|
|
15635
|
+
const override = this.config.per_server_overrides?.[serverName];
|
|
15636
|
+
if (!override) return this.config;
|
|
15637
|
+
return { ...this.config, ...override };
|
|
15638
|
+
}
|
|
15639
|
+
/**
|
|
15640
|
+
* Compute a SHA-256 hash of server + tool + canonical args.
|
|
15641
|
+
* Used for duplicate detection.
|
|
15642
|
+
*/
|
|
15643
|
+
computeCallHash(serverName, toolName, args) {
|
|
15644
|
+
const stableArgs = this.stableStringify(args);
|
|
15645
|
+
const input = `${serverName}\0${toolName}\0${stableArgs}`;
|
|
15646
|
+
return sha256Hex(input);
|
|
15647
|
+
}
|
|
15648
|
+
/**
|
|
15649
|
+
* Deterministic JSON serialization with sorted keys.
|
|
15650
|
+
*/
|
|
15651
|
+
stableStringify(obj) {
|
|
15652
|
+
if (obj === null || obj === void 0) return "null";
|
|
15653
|
+
if (typeof obj !== "object") return JSON.stringify(obj);
|
|
15654
|
+
if (Array.isArray(obj)) {
|
|
15655
|
+
return "[" + obj.map((item) => this.stableStringify(item)).join(",") + "]";
|
|
15656
|
+
}
|
|
15657
|
+
const sortedKeys = Object.keys(obj).sort();
|
|
15658
|
+
const pairs = sortedKeys.map(
|
|
15659
|
+
(key) => JSON.stringify(key) + ":" + this.stableStringify(obj[key])
|
|
15660
|
+
);
|
|
15661
|
+
return "{" + pairs.join(",") + "}";
|
|
15662
|
+
}
|
|
15663
|
+
/**
|
|
15664
|
+
* Prune volume window entries older than the window size.
|
|
15665
|
+
* Uses shift() from the front — timestamps are appended in order.
|
|
15666
|
+
*/
|
|
15667
|
+
pruneVolumeWindow(now, windowMs) {
|
|
15668
|
+
const cutoff = now - windowMs;
|
|
15669
|
+
while (this.volumeWindow.length > 0 && this.volumeWindow[0] < cutoff) {
|
|
15670
|
+
this.volumeWindow.shift();
|
|
15671
|
+
}
|
|
15672
|
+
}
|
|
15673
|
+
/**
|
|
15674
|
+
* Prune a per-tool rate window.
|
|
15675
|
+
*/
|
|
15676
|
+
pruneRateWindow(toolKey, now, windowMs) {
|
|
15677
|
+
const window = this.rateWindows.get(toolKey);
|
|
15678
|
+
if (!window) return;
|
|
15679
|
+
const cutoff = now - windowMs;
|
|
15680
|
+
while (window.length > 0 && window[0] < cutoff) {
|
|
15681
|
+
window.shift();
|
|
15682
|
+
}
|
|
15683
|
+
if (window.length === 0) {
|
|
15684
|
+
this.rateWindows.delete(toolKey);
|
|
15685
|
+
}
|
|
15686
|
+
}
|
|
15687
|
+
/**
|
|
15688
|
+
* Prune expired entries from the duplicate cache.
|
|
15689
|
+
* Amortized O(1) — only prunes when cache exceeds a size threshold.
|
|
15690
|
+
*/
|
|
15691
|
+
pruneDuplicateCache(now) {
|
|
15692
|
+
if (this.duplicateCache.size < 100) return;
|
|
15693
|
+
for (const [key, entry] of this.duplicateCache) {
|
|
15694
|
+
if (entry.expires_at <= now) {
|
|
15695
|
+
this.duplicateCache.delete(key);
|
|
15696
|
+
}
|
|
15697
|
+
}
|
|
15698
|
+
}
|
|
15699
|
+
};
|
|
15700
|
+
|
|
15701
|
+
// src/l2-operational/governor-tools.ts
|
|
15702
|
+
function createGovernorTools(governor, auditLog) {
|
|
15703
|
+
const tools = [
|
|
15704
|
+
// ── Governor Status ─────────────────────────────────────────────
|
|
15705
|
+
{
|
|
15706
|
+
name: "sanctuary/governor_status",
|
|
15707
|
+
description: "View the current Call Governor status including volume counters, per-tool rate counts, duplicate cache size, and lifetime counter. Use this to monitor tool call consumption, detect potential loops, and check how close you are to governance limits. The governor protects against runaway tool calls by enforcing volume limits, rate limits, duplicate detection, and a session lifetime cap.",
|
|
15708
|
+
inputSchema: {
|
|
15709
|
+
type: "object",
|
|
15710
|
+
properties: {}
|
|
15711
|
+
},
|
|
15712
|
+
handler: async () => {
|
|
15713
|
+
const status = governor.getStatus();
|
|
15714
|
+
auditLog.append("l2", "governor_status", "system", {
|
|
15715
|
+
volume_current: status.volume_current,
|
|
15716
|
+
volume_limit: status.volume_limit,
|
|
15717
|
+
lifetime_current: status.lifetime_current,
|
|
15718
|
+
lifetime_limit: status.lifetime_limit,
|
|
15719
|
+
duplicate_cache_size: status.duplicate_cache_size,
|
|
15720
|
+
hard_stopped: status.hard_stopped
|
|
15721
|
+
});
|
|
15722
|
+
const volumePercent = status.volume_limit > 0 ? Math.round(status.volume_current / status.volume_limit * 100) : 0;
|
|
15723
|
+
const lifetimePercent = status.lifetime_limit > 0 ? Math.round(status.lifetime_current / status.lifetime_limit * 100) : 0;
|
|
15724
|
+
const toolRateEntries = Object.entries(status.rate_by_tool);
|
|
15725
|
+
const highRateTools = toolRateEntries.filter(([, count]) => count > 10).map(([tool, count]) => `${tool} (${count} calls/min)`);
|
|
15726
|
+
return toolResult({
|
|
15727
|
+
governor_status: status,
|
|
15728
|
+
summary: {
|
|
15729
|
+
volume_usage: `${status.volume_current}/${status.volume_limit} (${volumePercent}%)`,
|
|
15730
|
+
lifetime_usage: `${status.lifetime_current}/${status.lifetime_limit} (${lifetimePercent}%)`,
|
|
15731
|
+
active_tools: toolRateEntries.length,
|
|
15732
|
+
cached_duplicates: status.duplicate_cache_size
|
|
15733
|
+
},
|
|
15734
|
+
warnings: [
|
|
15735
|
+
...status.hard_stopped ? ["HARD STOP: Lifetime limit reached. Use sanctuary/governor_reset to continue."] : [],
|
|
15736
|
+
...volumePercent > 80 ? [`Volume usage at ${volumePercent}% \u2014 approaching limit.`] : [],
|
|
15737
|
+
...lifetimePercent > 80 ? [`Lifetime usage at ${lifetimePercent}% \u2014 approaching hard stop.`] : [],
|
|
15738
|
+
...highRateTools.length > 0 ? [`High-rate tools detected: ${highRateTools.join(", ")}`] : []
|
|
15739
|
+
],
|
|
15740
|
+
guidance: status.hard_stopped ? "The governor has stopped all proxied tool calls because the session lifetime limit was reached. Use sanctuary/governor_reset (requires human approval) to reset counters and resume." : "The governor is monitoring all proxied tool calls. Counters reset automatically on server restart."
|
|
15741
|
+
});
|
|
15742
|
+
}
|
|
15743
|
+
},
|
|
15744
|
+
// ── Governor Reset ──────────────────────────────────────────────
|
|
15745
|
+
{
|
|
15746
|
+
name: "sanctuary/governor_reset",
|
|
15747
|
+
description: "Reset all Call Governor counters: volume window, per-tool rate windows, duplicate cache, and lifetime counter. This clears the hard stop if the lifetime limit was reached. This is a Tier 1 operation \u2014 requires human approval because it removes all runtime governance state and could allow previously blocked behavior to resume.",
|
|
15748
|
+
inputSchema: {
|
|
15749
|
+
type: "object",
|
|
15750
|
+
properties: {
|
|
15751
|
+
confirm: {
|
|
15752
|
+
type: "boolean",
|
|
15753
|
+
description: "Must be true to confirm the reset. This clears all governor state including the lifetime counter."
|
|
15754
|
+
}
|
|
15755
|
+
},
|
|
15756
|
+
required: ["confirm"]
|
|
15757
|
+
},
|
|
15758
|
+
handler: async (args) => {
|
|
15759
|
+
const confirm = args.confirm;
|
|
15760
|
+
if (!confirm) {
|
|
15761
|
+
return toolResult({
|
|
15762
|
+
error: "confirmation_required",
|
|
15763
|
+
message: "Set confirm: true to reset all governor counters. This will clear volume limits, rate tracking, duplicate cache, and the lifetime counter."
|
|
15764
|
+
});
|
|
15765
|
+
}
|
|
15766
|
+
const preResetStatus = governor.getStatus();
|
|
15767
|
+
governor.reset();
|
|
15768
|
+
const postResetStatus = governor.getStatus();
|
|
15769
|
+
auditLog.append("l2", "governor_reset", "system", {
|
|
15770
|
+
pre_reset: {
|
|
15771
|
+
volume_current: preResetStatus.volume_current,
|
|
15772
|
+
lifetime_current: preResetStatus.lifetime_current,
|
|
15773
|
+
duplicate_cache_size: preResetStatus.duplicate_cache_size,
|
|
15774
|
+
hard_stopped: preResetStatus.hard_stopped
|
|
15775
|
+
},
|
|
15776
|
+
post_reset: {
|
|
15777
|
+
volume_current: postResetStatus.volume_current,
|
|
15778
|
+
lifetime_current: postResetStatus.lifetime_current,
|
|
15779
|
+
duplicate_cache_size: postResetStatus.duplicate_cache_size,
|
|
15780
|
+
hard_stopped: postResetStatus.hard_stopped
|
|
15781
|
+
}
|
|
15782
|
+
});
|
|
15783
|
+
return toolResult({
|
|
15784
|
+
reset: true,
|
|
15785
|
+
previous_state: {
|
|
15786
|
+
lifetime_calls: preResetStatus.lifetime_current,
|
|
15787
|
+
was_hard_stopped: preResetStatus.hard_stopped,
|
|
15788
|
+
volume_at_reset: preResetStatus.volume_current,
|
|
15789
|
+
cached_duplicates_cleared: preResetStatus.duplicate_cache_size
|
|
15790
|
+
},
|
|
15791
|
+
current_state: postResetStatus,
|
|
15792
|
+
message: "All governor counters have been reset. " + (preResetStatus.hard_stopped ? "Hard stop has been cleared \u2014 proxied tool calls will resume." : "Volume, rate, duplicate, and lifetime counters are now at zero.")
|
|
15793
|
+
});
|
|
15794
|
+
}
|
|
15795
|
+
}
|
|
15796
|
+
];
|
|
15797
|
+
return { tools };
|
|
15798
|
+
}
|
|
15799
|
+
|
|
15800
|
+
// src/index.ts
|
|
15801
|
+
init_random();
|
|
15802
|
+
init_encoding();
|
|
15803
|
+
|
|
15804
|
+
// src/l2-operational/model-provenance.ts
|
|
15805
|
+
var InMemoryModelProvenanceStore = class {
|
|
15806
|
+
models = /* @__PURE__ */ new Map();
|
|
15807
|
+
primaryModelId = null;
|
|
15808
|
+
declare(provenance) {
|
|
15809
|
+
if (!provenance.model_id) {
|
|
15810
|
+
throw new Error("ModelProvenance requires a model_id");
|
|
15811
|
+
}
|
|
15812
|
+
if (!provenance.model_name) {
|
|
15813
|
+
throw new Error("ModelProvenance requires a model_name");
|
|
13355
15814
|
}
|
|
13356
15815
|
if (!provenance.provider) {
|
|
13357
15816
|
throw new Error("ModelProvenance requires a provider");
|
|
@@ -13958,18 +16417,89 @@ async function createSanctuaryServer(options) {
|
|
|
13958
16417
|
...dashboardTools,
|
|
13959
16418
|
manifestTool
|
|
13960
16419
|
];
|
|
16420
|
+
let clientManager;
|
|
16421
|
+
let proxyRouter;
|
|
16422
|
+
const governor = new CallGovernor();
|
|
16423
|
+
const { tools: governorTools } = createGovernorTools(governor, auditLog);
|
|
16424
|
+
allTools.push(...governorTools);
|
|
16425
|
+
const profile = profileStore.get();
|
|
16426
|
+
if (profile.upstream_servers && profile.upstream_servers.length > 0) {
|
|
16427
|
+
const enabledServers = profile.upstream_servers.filter((s) => s.enabled);
|
|
16428
|
+
if (enabledServers.length > 0) {
|
|
16429
|
+
clientManager = new ClientManager({
|
|
16430
|
+
onStateChange: (serverName, state, toolCount, error) => {
|
|
16431
|
+
if (dashboard) {
|
|
16432
|
+
dashboard.broadcastSSE("proxy-server-status", {
|
|
16433
|
+
server: serverName,
|
|
16434
|
+
state,
|
|
16435
|
+
tool_count: toolCount,
|
|
16436
|
+
error,
|
|
16437
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
16438
|
+
});
|
|
16439
|
+
}
|
|
16440
|
+
auditLog.append("l2", `proxy_server_${state}`, "system", {
|
|
16441
|
+
server: serverName,
|
|
16442
|
+
tool_count: toolCount,
|
|
16443
|
+
error
|
|
16444
|
+
});
|
|
16445
|
+
}
|
|
16446
|
+
});
|
|
16447
|
+
proxyRouter = new ProxyRouter(
|
|
16448
|
+
clientManager,
|
|
16449
|
+
injectionDetector,
|
|
16450
|
+
auditLog,
|
|
16451
|
+
{
|
|
16452
|
+
contextGateFilter: async (_toolName, args) => {
|
|
16453
|
+
const activeProfile = profileStore.get();
|
|
16454
|
+
if (activeProfile.features.context_gating.enabled) {
|
|
16455
|
+
return args;
|
|
16456
|
+
}
|
|
16457
|
+
return args;
|
|
16458
|
+
},
|
|
16459
|
+
governor
|
|
16460
|
+
}
|
|
16461
|
+
);
|
|
16462
|
+
clientManager.configure(enabledServers).catch((err) => {
|
|
16463
|
+
console.error(`[Sanctuary] Failed to configure upstream servers: ${err instanceof Error ? err.message : "unknown error"}`);
|
|
16464
|
+
});
|
|
16465
|
+
await new Promise((resolve) => setTimeout(resolve, 2e3));
|
|
16466
|
+
const proxiedTools = proxyRouter.getProxiedTools();
|
|
16467
|
+
if (proxiedTools.length > 0) {
|
|
16468
|
+
allTools.push(...proxiedTools);
|
|
16469
|
+
}
|
|
16470
|
+
if (dashboard) {
|
|
16471
|
+
dashboard.setDependencies({
|
|
16472
|
+
policy,
|
|
16473
|
+
baseline,
|
|
16474
|
+
auditLog,
|
|
16475
|
+
clientManager
|
|
16476
|
+
});
|
|
16477
|
+
}
|
|
16478
|
+
}
|
|
16479
|
+
}
|
|
13961
16480
|
allTools = allTools.map((tool) => ({
|
|
13962
16481
|
...tool,
|
|
13963
16482
|
handler: contextGateEnforcer.wrapHandler(tool.name, tool.handler)
|
|
13964
16483
|
}));
|
|
16484
|
+
if (proxyRouter) {
|
|
16485
|
+
gate.setProxyTierResolver((toolName) => {
|
|
16486
|
+
const parsed = ProxyRouter.parseProxyToolName(toolName);
|
|
16487
|
+
if (!parsed) return null;
|
|
16488
|
+
return proxyRouter.getTierForTool(parsed.serverName, parsed.toolName);
|
|
16489
|
+
});
|
|
16490
|
+
}
|
|
13965
16491
|
const server = createServer(allTools, { gate });
|
|
13966
16492
|
await saveConfig(config);
|
|
13967
|
-
const
|
|
16493
|
+
const cleanup = () => {
|
|
13968
16494
|
baseline.save().catch(() => {
|
|
13969
16495
|
});
|
|
16496
|
+
if (clientManager) {
|
|
16497
|
+
clientManager.shutdown().catch(() => {
|
|
16498
|
+
});
|
|
16499
|
+
}
|
|
13970
16500
|
};
|
|
13971
|
-
process.on("SIGINT",
|
|
13972
|
-
process.on("SIGTERM",
|
|
16501
|
+
process.on("SIGINT", cleanup);
|
|
16502
|
+
process.on("SIGTERM", cleanup);
|
|
13973
16503
|
if (recoveryKey) {
|
|
13974
16504
|
console.error(
|
|
13975
16505
|
`\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
@@ -13985,6 +16515,6 @@ async function createSanctuaryServer(options) {
|
|
|
13985
16515
|
return { server, config };
|
|
13986
16516
|
}
|
|
13987
16517
|
|
|
13988
|
-
export { ATTESTATION_VERSION, ApprovalGate, AuditLog, AutoApproveChannel, BaselineTracker, TEMPLATES as CONTEXT_GATE_TEMPLATES, CallbackApprovalChannel, CommitmentStore, ContextGateEnforcer, ContextGatePolicyStore, DashboardApprovalChannel, FederationRegistry, FilesystemStorage, InMemoryModelProvenanceStore, InjectionDetector, MODEL_PRESETS, MemoryStorage, PolicyStore, ReputationStore, SovereigntyProfileStore, StateStore, StderrApprovalChannel, TIER_WEIGHTS, WebhookApprovalChannel, canonicalize, classifyField, completeHandshake, computeWeightedScore, createBridgeCommitment, createDefaultProfile, createPedersenCommitment, createProofOfKnowledge, createRangeProof, createSanctuaryServer, evaluateField, filterContext, generateAttestation, generateSHR, generateSystemPrompt, getTemplate, initiateHandshake, listTemplateIds, loadConfig, loadPrincipalPolicy, recommendPolicy, resolveTier, respondToHandshake, signPayload, tierDistribution, verifyAttestation, verifyBridgeCommitment, verifyCompletion, verifyPedersenCommitment, verifyProofOfKnowledge, verifyRangeProof, verifySHR, verifySignature };
|
|
16518
|
+
export { ATTESTATION_VERSION, ApprovalGate, AuditLog, AutoApproveChannel, BaselineTracker, TEMPLATES as CONTEXT_GATE_TEMPLATES, CallbackApprovalChannel, ClientManager, CommitmentStore, ContextGateEnforcer, ContextGatePolicyStore, DashboardApprovalChannel, FederationRegistry, FilesystemStorage, InMemoryModelProvenanceStore, InjectionDetector, MODEL_PRESETS, MemoryStorage, PolicyStore, ProxyRouter, ReputationStore, SovereigntyProfileStore, StateStore, StderrApprovalChannel, TIER_WEIGHTS, WebhookApprovalChannel, canonicalize, classifyField, completeHandshake, computeWeightedScore, createBridgeCommitment, createDefaultProfile, createPedersenCommitment, createProofOfKnowledge, createRangeProof, createSanctuaryServer, evaluateField, filterContext, generateAttestation, generateSHR, generateSystemPrompt, getTemplate, initiateHandshake, listTemplateIds, loadConfig, loadPrincipalPolicy, recommendPolicy, resolveTier, respondToHandshake, signPayload, tierDistribution, verifyAttestation, verifyBridgeCommitment, verifyCompletion, verifyPedersenCommitment, verifyProofOfKnowledge, verifyRangeProof, verifySHR, verifySignature };
|
|
13989
16519
|
//# sourceMappingURL=index.js.map
|
|
13990
16520
|
//# sourceMappingURL=index.js.map
|