@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/cli.js
CHANGED
|
@@ -17,6 +17,9 @@ import { get, createServer as createServer$2 } from 'https';
|
|
|
17
17
|
import { statSync, readFileSync } from 'fs';
|
|
18
18
|
import { execSync, exec } from 'child_process';
|
|
19
19
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
20
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
21
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
22
|
+
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
|
|
20
23
|
|
|
21
24
|
var __defProp = Object.defineProperty;
|
|
22
25
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
@@ -1534,6 +1537,9 @@ var init_audit_log = __esm({
|
|
|
1534
1537
|
}
|
|
1535
1538
|
});
|
|
1536
1539
|
function extractOperationName(toolName) {
|
|
1540
|
+
if (toolName.startsWith("proxy/")) {
|
|
1541
|
+
return toolName;
|
|
1542
|
+
}
|
|
1537
1543
|
return toolName.startsWith("sanctuary/") ? toolName.slice("sanctuary/".length) : toolName;
|
|
1538
1544
|
}
|
|
1539
1545
|
function parsePolicy(content) {
|
|
@@ -1639,6 +1645,7 @@ tier1_always_approve:
|
|
|
1639
1645
|
- bootstrap_provide_guarantee
|
|
1640
1646
|
- reputation_publish
|
|
1641
1647
|
- sovereignty_profile_update
|
|
1648
|
+
- governor_reset
|
|
1642
1649
|
|
|
1643
1650
|
# \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
|
|
1644
1651
|
# Triggers approval when agent behavior deviates from its baseline.
|
|
@@ -1703,7 +1710,7 @@ tier3_always_allow:
|
|
|
1703
1710
|
- bridge_attest
|
|
1704
1711
|
- dashboard_open
|
|
1705
1712
|
- sovereignty_profile_get
|
|
1706
|
-
-
|
|
1713
|
+
- governor_status
|
|
1707
1714
|
|
|
1708
1715
|
# \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
|
|
1709
1716
|
# How Sanctuary reaches you when approval is needed.
|
|
@@ -1759,8 +1766,10 @@ var init_loader = __esm({
|
|
|
1759
1766
|
"decommission_certificate",
|
|
1760
1767
|
"reputation_publish",
|
|
1761
1768
|
// SEC-039: Explicit Tier 1 — sends data to external API
|
|
1762
|
-
"sovereignty_profile_update"
|
|
1769
|
+
"sovereignty_profile_update",
|
|
1763
1770
|
// Changes enforcement behavior — always requires approval
|
|
1771
|
+
"governor_reset"
|
|
1772
|
+
// Clears all runtime governance state — always requires approval
|
|
1764
1773
|
],
|
|
1765
1774
|
tier2_anomaly: DEFAULT_TIER2,
|
|
1766
1775
|
tier3_always_allow: [
|
|
@@ -1816,7 +1825,9 @@ var init_loader = __esm({
|
|
|
1816
1825
|
"dashboard_open",
|
|
1817
1826
|
// SEC-039: Explicit Tier 3 — only generates a URL
|
|
1818
1827
|
"sovereignty_profile_get",
|
|
1819
|
-
"sovereignty_profile_generate_prompt"
|
|
1828
|
+
"sovereignty_profile_generate_prompt",
|
|
1829
|
+
// Agent needs its own config to generate system prompt
|
|
1830
|
+
"governor_status"
|
|
1820
1831
|
],
|
|
1821
1832
|
approval_channel: DEFAULT_CHANNEL
|
|
1822
1833
|
};
|
|
@@ -3069,6 +3080,17 @@ function generateDashboardHTML(options) {
|
|
|
3069
3080
|
display: flex;
|
|
3070
3081
|
flex-direction: column;
|
|
3071
3082
|
gap: 8px;
|
|
3083
|
+
transition: border-color 0.2s;
|
|
3084
|
+
}
|
|
3085
|
+
|
|
3086
|
+
.profile-card.active {
|
|
3087
|
+
border-color: var(--green);
|
|
3088
|
+
}
|
|
3089
|
+
|
|
3090
|
+
.profile-card-header {
|
|
3091
|
+
display: flex;
|
|
3092
|
+
justify-content: space-between;
|
|
3093
|
+
align-items: center;
|
|
3072
3094
|
}
|
|
3073
3095
|
|
|
3074
3096
|
.profile-card-name {
|
|
@@ -3083,6 +3105,53 @@ function generateDashboardHTML(options) {
|
|
|
3083
3105
|
line-height: 1.4;
|
|
3084
3106
|
}
|
|
3085
3107
|
|
|
3108
|
+
/* Toggle switch */
|
|
3109
|
+
.toggle-switch {
|
|
3110
|
+
position: relative;
|
|
3111
|
+
width: 36px;
|
|
3112
|
+
height: 20px;
|
|
3113
|
+
flex-shrink: 0;
|
|
3114
|
+
}
|
|
3115
|
+
|
|
3116
|
+
.toggle-switch input {
|
|
3117
|
+
opacity: 0;
|
|
3118
|
+
width: 0;
|
|
3119
|
+
height: 0;
|
|
3120
|
+
}
|
|
3121
|
+
|
|
3122
|
+
.toggle-slider {
|
|
3123
|
+
position: absolute;
|
|
3124
|
+
cursor: pointer;
|
|
3125
|
+
top: 0;
|
|
3126
|
+
left: 0;
|
|
3127
|
+
right: 0;
|
|
3128
|
+
bottom: 0;
|
|
3129
|
+
background-color: var(--border);
|
|
3130
|
+
border-radius: 10px;
|
|
3131
|
+
transition: background-color 0.2s;
|
|
3132
|
+
}
|
|
3133
|
+
|
|
3134
|
+
.toggle-slider::before {
|
|
3135
|
+
content: "";
|
|
3136
|
+
position: absolute;
|
|
3137
|
+
height: 14px;
|
|
3138
|
+
width: 14px;
|
|
3139
|
+
left: 3px;
|
|
3140
|
+
bottom: 3px;
|
|
3141
|
+
background-color: var(--text-secondary);
|
|
3142
|
+
border-radius: 50%;
|
|
3143
|
+
transition: transform 0.2s, background-color 0.2s;
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
.toggle-switch input:checked + .toggle-slider {
|
|
3147
|
+
background-color: rgba(63, 185, 80, 0.3);
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
.toggle-switch input:checked + .toggle-slider::before {
|
|
3151
|
+
transform: translateX(16px);
|
|
3152
|
+
background-color: var(--green);
|
|
3153
|
+
}
|
|
3154
|
+
|
|
3086
3155
|
.profile-badge {
|
|
3087
3156
|
display: inline-flex;
|
|
3088
3157
|
align-items: center;
|
|
@@ -3104,22 +3173,159 @@ function generateDashboardHTML(options) {
|
|
|
3104
3173
|
color: var(--text-secondary);
|
|
3105
3174
|
}
|
|
3106
3175
|
|
|
3176
|
+
.profile-card-actions {
|
|
3177
|
+
display: flex;
|
|
3178
|
+
gap: 6px;
|
|
3179
|
+
margin-top: 4px;
|
|
3180
|
+
}
|
|
3181
|
+
|
|
3182
|
+
.config-btn {
|
|
3183
|
+
padding: 3px 8px;
|
|
3184
|
+
border: 1px solid var(--border);
|
|
3185
|
+
border-radius: 4px;
|
|
3186
|
+
background-color: transparent;
|
|
3187
|
+
color: var(--text-secondary);
|
|
3188
|
+
font-size: 10px;
|
|
3189
|
+
cursor: pointer;
|
|
3190
|
+
transition: color 0.2s, border-color 0.2s;
|
|
3191
|
+
}
|
|
3192
|
+
|
|
3193
|
+
.config-btn:hover {
|
|
3194
|
+
color: var(--blue);
|
|
3195
|
+
border-color: var(--blue);
|
|
3196
|
+
}
|
|
3197
|
+
|
|
3198
|
+
/* Configuration panels */
|
|
3199
|
+
.config-panel {
|
|
3200
|
+
display: none;
|
|
3201
|
+
margin-top: 8px;
|
|
3202
|
+
padding: 10px;
|
|
3203
|
+
background-color: var(--surface);
|
|
3204
|
+
border: 1px solid var(--border);
|
|
3205
|
+
border-radius: 4px;
|
|
3206
|
+
font-size: 11px;
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
.config-panel.open {
|
|
3210
|
+
display: block;
|
|
3211
|
+
}
|
|
3212
|
+
|
|
3213
|
+
.config-panel-title {
|
|
3214
|
+
font-size: 11px;
|
|
3215
|
+
font-weight: 600;
|
|
3216
|
+
color: var(--text-primary);
|
|
3217
|
+
margin-bottom: 8px;
|
|
3218
|
+
}
|
|
3219
|
+
|
|
3220
|
+
.config-row {
|
|
3221
|
+
display: flex;
|
|
3222
|
+
align-items: center;
|
|
3223
|
+
gap: 8px;
|
|
3224
|
+
margin-bottom: 6px;
|
|
3225
|
+
}
|
|
3226
|
+
|
|
3227
|
+
.config-label {
|
|
3228
|
+
font-size: 11px;
|
|
3229
|
+
color: var(--text-secondary);
|
|
3230
|
+
min-width: 80px;
|
|
3231
|
+
}
|
|
3232
|
+
|
|
3233
|
+
.config-select, .config-input {
|
|
3234
|
+
background-color: var(--bg);
|
|
3235
|
+
border: 1px solid var(--border);
|
|
3236
|
+
border-radius: 4px;
|
|
3237
|
+
color: var(--text-primary);
|
|
3238
|
+
font-size: 11px;
|
|
3239
|
+
padding: 4px 8px;
|
|
3240
|
+
}
|
|
3241
|
+
|
|
3242
|
+
.config-info {
|
|
3243
|
+
font-size: 11px;
|
|
3244
|
+
color: var(--text-secondary);
|
|
3245
|
+
line-height: 1.5;
|
|
3246
|
+
}
|
|
3247
|
+
|
|
3248
|
+
.sensitivity-slider {
|
|
3249
|
+
display: flex;
|
|
3250
|
+
gap: 4px;
|
|
3251
|
+
}
|
|
3252
|
+
|
|
3253
|
+
.sensitivity-option {
|
|
3254
|
+
padding: 3px 10px;
|
|
3255
|
+
border: 1px solid var(--border);
|
|
3256
|
+
border-radius: 4px;
|
|
3257
|
+
background-color: transparent;
|
|
3258
|
+
color: var(--text-secondary);
|
|
3259
|
+
font-size: 10px;
|
|
3260
|
+
cursor: pointer;
|
|
3261
|
+
transition: all 0.2s;
|
|
3262
|
+
}
|
|
3263
|
+
|
|
3264
|
+
.sensitivity-option.selected {
|
|
3265
|
+
background-color: rgba(88, 166, 255, 0.15);
|
|
3266
|
+
color: var(--blue);
|
|
3267
|
+
border-color: var(--blue);
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
.sensitivity-option:hover:not(.selected) {
|
|
3271
|
+
border-color: var(--text-secondary);
|
|
3272
|
+
}
|
|
3273
|
+
|
|
3274
|
+
/* Prompt section */
|
|
3107
3275
|
.prompt-section {
|
|
3108
|
-
margin-top:
|
|
3276
|
+
margin-top: 16px;
|
|
3109
3277
|
}
|
|
3110
3278
|
|
|
3111
|
-
.prompt-
|
|
3112
|
-
|
|
3113
|
-
min-height: 120px;
|
|
3279
|
+
.prompt-display {
|
|
3280
|
+
position: relative;
|
|
3114
3281
|
background-color: var(--bg);
|
|
3115
3282
|
border: 1px solid var(--border);
|
|
3116
3283
|
border-radius: 6px;
|
|
3284
|
+
margin-top: 8px;
|
|
3285
|
+
display: none;
|
|
3286
|
+
}
|
|
3287
|
+
|
|
3288
|
+
.prompt-display.visible {
|
|
3289
|
+
display: block;
|
|
3290
|
+
}
|
|
3291
|
+
|
|
3292
|
+
.prompt-display-header {
|
|
3293
|
+
display: flex;
|
|
3294
|
+
justify-content: space-between;
|
|
3295
|
+
align-items: center;
|
|
3296
|
+
padding: 8px 12px;
|
|
3297
|
+
border-bottom: 1px solid var(--border);
|
|
3298
|
+
}
|
|
3299
|
+
|
|
3300
|
+
.prompt-token-count {
|
|
3301
|
+
font-size: 11px;
|
|
3302
|
+
color: var(--text-secondary);
|
|
3303
|
+
}
|
|
3304
|
+
|
|
3305
|
+
.prompt-copy-btn {
|
|
3306
|
+
padding: 4px 10px;
|
|
3307
|
+
border: 1px solid var(--border);
|
|
3308
|
+
border-radius: 4px;
|
|
3309
|
+
background-color: var(--surface);
|
|
3117
3310
|
color: var(--text-primary);
|
|
3311
|
+
font-size: 11px;
|
|
3312
|
+
cursor: pointer;
|
|
3313
|
+
transition: border-color 0.2s;
|
|
3314
|
+
}
|
|
3315
|
+
|
|
3316
|
+
.prompt-copy-btn:hover {
|
|
3317
|
+
border-color: var(--blue);
|
|
3318
|
+
}
|
|
3319
|
+
|
|
3320
|
+
.prompt-content {
|
|
3321
|
+
max-height: 300px;
|
|
3322
|
+
overflow-y: auto;
|
|
3323
|
+
padding: 12px;
|
|
3118
3324
|
font-family: 'JetBrains Mono', monospace;
|
|
3119
3325
|
font-size: 12px;
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3326
|
+
line-height: 1.6;
|
|
3327
|
+
white-space: pre-wrap;
|
|
3328
|
+
color: var(--text-primary);
|
|
3123
3329
|
}
|
|
3124
3330
|
|
|
3125
3331
|
.prompt-actions {
|
|
@@ -3506,37 +3712,173 @@ function generateDashboardHTML(options) {
|
|
|
3506
3712
|
</div>
|
|
3507
3713
|
<div class="profile-cards" id="profile-cards">
|
|
3508
3714
|
<div class="profile-card" data-feature="audit_logging">
|
|
3509
|
-
<div class="profile-card-
|
|
3715
|
+
<div class="profile-card-header">
|
|
3716
|
+
<div class="profile-card-name">Audit Logging</div>
|
|
3717
|
+
<label class="toggle-switch">
|
|
3718
|
+
<input type="checkbox" id="toggle-audit_logging" data-feature="audit_logging">
|
|
3719
|
+
<span class="toggle-slider"></span>
|
|
3720
|
+
</label>
|
|
3721
|
+
</div>
|
|
3510
3722
|
<div class="profile-badge disabled" id="badge-audit_logging">OFF</div>
|
|
3511
3723
|
<div class="profile-card-desc">Encrypted audit trail of all tool calls</div>
|
|
3724
|
+
<div class="profile-card-actions">
|
|
3725
|
+
<button class="config-btn" data-config="audit_logging">Configure</button>
|
|
3726
|
+
</div>
|
|
3727
|
+
<div class="config-panel" id="config-audit_logging">
|
|
3728
|
+
<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>
|
|
3729
|
+
</div>
|
|
3512
3730
|
</div>
|
|
3513
3731
|
<div class="profile-card" data-feature="injection_detection">
|
|
3514
|
-
<div class="profile-card-
|
|
3732
|
+
<div class="profile-card-header">
|
|
3733
|
+
<div class="profile-card-name">Injection Detection</div>
|
|
3734
|
+
<label class="toggle-switch">
|
|
3735
|
+
<input type="checkbox" id="toggle-injection_detection" data-feature="injection_detection">
|
|
3736
|
+
<span class="toggle-slider"></span>
|
|
3737
|
+
</label>
|
|
3738
|
+
</div>
|
|
3515
3739
|
<div class="profile-badge disabled" id="badge-injection_detection">OFF</div>
|
|
3516
3740
|
<div class="profile-card-desc">Scans tool arguments for prompt injection</div>
|
|
3741
|
+
<div class="profile-card-actions">
|
|
3742
|
+
<button class="config-btn" data-config="injection_detection">Configure</button>
|
|
3743
|
+
</div>
|
|
3744
|
+
<div class="config-panel" id="config-injection_detection">
|
|
3745
|
+
<div class="config-panel-title">Sensitivity</div>
|
|
3746
|
+
<div class="sensitivity-slider">
|
|
3747
|
+
<button class="sensitivity-option" data-sensitivity="low">Low</button>
|
|
3748
|
+
<button class="sensitivity-option selected" data-sensitivity="medium">Medium</button>
|
|
3749
|
+
<button class="sensitivity-option" data-sensitivity="high">High</button>
|
|
3750
|
+
</div>
|
|
3751
|
+
</div>
|
|
3517
3752
|
</div>
|
|
3518
3753
|
<div class="profile-card" data-feature="context_gating">
|
|
3519
|
-
<div class="profile-card-
|
|
3754
|
+
<div class="profile-card-header">
|
|
3755
|
+
<div class="profile-card-name">Context Gating</div>
|
|
3756
|
+
<label class="toggle-switch">
|
|
3757
|
+
<input type="checkbox" id="toggle-context_gating" data-feature="context_gating">
|
|
3758
|
+
<span class="toggle-slider"></span>
|
|
3759
|
+
</label>
|
|
3760
|
+
</div>
|
|
3520
3761
|
<div class="profile-badge disabled" id="badge-context_gating">OFF</div>
|
|
3521
3762
|
<div class="profile-card-desc">Controls context flow to remote providers</div>
|
|
3763
|
+
<div class="profile-card-actions">
|
|
3764
|
+
<button class="config-btn" data-config="context_gating">Configure</button>
|
|
3765
|
+
</div>
|
|
3766
|
+
<div class="config-panel" id="config-context_gating">
|
|
3767
|
+
<div class="config-panel-title">Active Policy</div>
|
|
3768
|
+
<div class="config-row">
|
|
3769
|
+
<span class="config-label">Policy ID:</span>
|
|
3770
|
+
<select class="config-select" id="config-context-policy">
|
|
3771
|
+
<option value="">None selected</option>
|
|
3772
|
+
</select>
|
|
3773
|
+
</div>
|
|
3774
|
+
<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>
|
|
3775
|
+
</div>
|
|
3522
3776
|
</div>
|
|
3523
3777
|
<div class="profile-card" data-feature="approval_gate">
|
|
3524
|
-
<div class="profile-card-
|
|
3778
|
+
<div class="profile-card-header">
|
|
3779
|
+
<div class="profile-card-name">Approval Gates</div>
|
|
3780
|
+
<label class="toggle-switch">
|
|
3781
|
+
<input type="checkbox" id="toggle-approval_gate" data-feature="approval_gate">
|
|
3782
|
+
<span class="toggle-slider"></span>
|
|
3783
|
+
</label>
|
|
3784
|
+
</div>
|
|
3525
3785
|
<div class="profile-badge disabled" id="badge-approval_gate">OFF</div>
|
|
3526
3786
|
<div class="profile-card-desc">Human approval for high-risk operations</div>
|
|
3787
|
+
<div class="profile-card-actions">
|
|
3788
|
+
<button class="config-btn" data-config="approval_gate">Configure</button>
|
|
3789
|
+
</div>
|
|
3790
|
+
<div class="config-panel" id="config-approval_gate">
|
|
3791
|
+
<div class="config-panel-title">Tier Assignments</div>
|
|
3792
|
+
<div class="config-info">
|
|
3793
|
+
<strong style="color: var(--red);">Tier 1 (always approve):</strong> export, import, key rotation, deletion<br>
|
|
3794
|
+
<strong style="color: var(--amber);">Tier 2 (approve on anomaly):</strong> new namespaces, unfamiliar counterparties, frequency spikes<br>
|
|
3795
|
+
<strong style="color: var(--green);">Tier 3 (auto-allow):</strong> standard operations, queries, reads
|
|
3796
|
+
</div>
|
|
3797
|
+
</div>
|
|
3527
3798
|
</div>
|
|
3528
3799
|
<div class="profile-card" data-feature="zk_proofs">
|
|
3529
|
-
<div class="profile-card-
|
|
3800
|
+
<div class="profile-card-header">
|
|
3801
|
+
<div class="profile-card-name">ZK Proofs</div>
|
|
3802
|
+
<label class="toggle-switch">
|
|
3803
|
+
<input type="checkbox" id="toggle-zk_proofs" data-feature="zk_proofs">
|
|
3804
|
+
<span class="toggle-slider"></span>
|
|
3805
|
+
</label>
|
|
3806
|
+
</div>
|
|
3530
3807
|
<div class="profile-badge disabled" id="badge-zk_proofs">OFF</div>
|
|
3531
3808
|
<div class="profile-card-desc">Prove claims without revealing data</div>
|
|
3809
|
+
<div class="profile-card-actions">
|
|
3810
|
+
<button class="config-btn" data-config="zk_proofs">Configure</button>
|
|
3811
|
+
</div>
|
|
3812
|
+
<div class="config-panel" id="config-zk_proofs">
|
|
3813
|
+
<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>
|
|
3814
|
+
</div>
|
|
3532
3815
|
</div>
|
|
3533
3816
|
</div>
|
|
3534
3817
|
<div class="prompt-section">
|
|
3535
3818
|
<div class="prompt-actions">
|
|
3536
3819
|
<button class="prompt-btn primary" id="generate-prompt-btn">Generate System Prompt</button>
|
|
3537
|
-
<button class="prompt-btn" id="copy-prompt-btn" style="display:none;">Copy</button>
|
|
3538
3820
|
</div>
|
|
3539
|
-
<
|
|
3821
|
+
<div class="prompt-display" id="prompt-display">
|
|
3822
|
+
<div class="prompt-display-header">
|
|
3823
|
+
<span class="prompt-token-count" id="prompt-token-count"></span>
|
|
3824
|
+
<button class="prompt-copy-btn" id="copy-prompt-btn">Copy to Clipboard</button>
|
|
3825
|
+
</div>
|
|
3826
|
+
<div class="prompt-content" id="system-prompt-output"></div>
|
|
3827
|
+
</div>
|
|
3828
|
+
</div>
|
|
3829
|
+
</div>
|
|
3830
|
+
|
|
3831
|
+
<!-- Upstream Servers Panel -->
|
|
3832
|
+
<div class="profile-panel" id="proxy-servers-panel">
|
|
3833
|
+
<div class="panel-header">
|
|
3834
|
+
<div class="panel-title">Upstream Servers</div>
|
|
3835
|
+
<button class="panel-action" id="add-proxy-server-btn">+ Add Server</button>
|
|
3836
|
+
</div>
|
|
3837
|
+
<div id="proxy-servers-list">
|
|
3838
|
+
<div class="empty-state">No upstream servers configured</div>
|
|
3839
|
+
</div>
|
|
3840
|
+
|
|
3841
|
+
<!-- Add Server Form (hidden by default) -->
|
|
3842
|
+
<div id="add-server-form" style="display: none; padding: 16px; border-top: 1px solid var(--border);">
|
|
3843
|
+
<div style="margin-bottom: 12px;">
|
|
3844
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Server Name</label>
|
|
3845
|
+
<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;">
|
|
3846
|
+
</div>
|
|
3847
|
+
<div style="margin-bottom: 12px;">
|
|
3848
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Transport Type</label>
|
|
3849
|
+
<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;">
|
|
3850
|
+
<option value="stdio">stdio</option>
|
|
3851
|
+
<option value="sse">SSE</option>
|
|
3852
|
+
</select>
|
|
3853
|
+
</div>
|
|
3854
|
+
<div id="stdio-fields">
|
|
3855
|
+
<div style="margin-bottom: 12px;">
|
|
3856
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Command</label>
|
|
3857
|
+
<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;">
|
|
3858
|
+
</div>
|
|
3859
|
+
<div style="margin-bottom: 12px;">
|
|
3860
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Arguments (comma-separated)</label>
|
|
3861
|
+
<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;">
|
|
3862
|
+
</div>
|
|
3863
|
+
</div>
|
|
3864
|
+
<div id="sse-fields" style="display: none;">
|
|
3865
|
+
<div style="margin-bottom: 12px;">
|
|
3866
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Server URL</label>
|
|
3867
|
+
<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;">
|
|
3868
|
+
</div>
|
|
3869
|
+
</div>
|
|
3870
|
+
<div style="margin-bottom: 12px;">
|
|
3871
|
+
<label style="font-size: 12px; color: var(--text-secondary); display: block; margin-bottom: 4px;">Default Tier</label>
|
|
3872
|
+
<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;">
|
|
3873
|
+
<option value="1">Tier 1 (Always approve)</option>
|
|
3874
|
+
<option value="2" selected>Tier 2 (Anomaly detection)</option>
|
|
3875
|
+
<option value="3">Tier 3 (Always allow)</option>
|
|
3876
|
+
</select>
|
|
3877
|
+
</div>
|
|
3878
|
+
<div style="display: flex; gap: 8px;">
|
|
3879
|
+
<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>
|
|
3880
|
+
<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>
|
|
3881
|
+
</div>
|
|
3540
3882
|
</div>
|
|
3541
3883
|
</div>
|
|
3542
3884
|
|
|
@@ -4027,8 +4369,34 @@ function generateDashboardHTML(options) {
|
|
|
4027
4369
|
removePendingRequest(data.requestId);
|
|
4028
4370
|
});
|
|
4029
4371
|
|
|
4030
|
-
eventSource.addEventListener('sovereignty-profile-update', () => {
|
|
4031
|
-
|
|
4372
|
+
eventSource.addEventListener('sovereignty-profile-update', (e) => {
|
|
4373
|
+
try {
|
|
4374
|
+
const data = JSON.parse(e.data);
|
|
4375
|
+
if (data.profile) {
|
|
4376
|
+
applyProfileToUI(data.profile);
|
|
4377
|
+
}
|
|
4378
|
+
if (data.system_prompt) {
|
|
4379
|
+
apiState.systemPrompt = data.system_prompt;
|
|
4380
|
+
updatePromptDisplay(data.system_prompt);
|
|
4381
|
+
}
|
|
4382
|
+
} catch (err) {
|
|
4383
|
+
// Fallback to full refresh
|
|
4384
|
+
updateSovereigntyProfile();
|
|
4385
|
+
}
|
|
4386
|
+
});
|
|
4387
|
+
|
|
4388
|
+
eventSource.addEventListener('proxy-server-status', (e) => {
|
|
4389
|
+
try {
|
|
4390
|
+
const data = JSON.parse(e.data);
|
|
4391
|
+
updateProxyServerStatus(data.server, data.state, data.tool_count, data.error);
|
|
4392
|
+
} catch (err) {
|
|
4393
|
+
// Fallback to full refresh
|
|
4394
|
+
loadProxyServers();
|
|
4395
|
+
}
|
|
4396
|
+
});
|
|
4397
|
+
|
|
4398
|
+
eventSource.addEventListener('proxy-servers-update', () => {
|
|
4399
|
+
loadProxyServers();
|
|
4032
4400
|
});
|
|
4033
4401
|
|
|
4034
4402
|
eventSource.onerror = () => {
|
|
@@ -4046,7 +4414,7 @@ function generateDashboardHTML(options) {
|
|
|
4046
4414
|
|
|
4047
4415
|
const feed = document.getElementById('activity-feed');
|
|
4048
4416
|
const html = \`
|
|
4049
|
-
<div class="activity-item \${item.type}">
|
|
4417
|
+
<div class="activity-item \${esc(item.type)}">
|
|
4050
4418
|
<div class="activity-type">\${esc(item.title)}</div>
|
|
4051
4419
|
<div class="activity-content">\${esc(item.content)}</div>
|
|
4052
4420
|
<div class="activity-time">\${formatTime(item.timestamp)}</div>
|
|
@@ -4188,26 +4556,16 @@ function generateDashboardHTML(options) {
|
|
|
4188
4556
|
});
|
|
4189
4557
|
|
|
4190
4558
|
// Sovereignty Profile
|
|
4559
|
+
let profileToggleLock = false;
|
|
4560
|
+
|
|
4191
4561
|
async function updateSovereigntyProfile() {
|
|
4192
4562
|
try {
|
|
4193
4563
|
const data = await fetchAPI('/api/sovereignty-profile');
|
|
4194
4564
|
if (data && data.profile) {
|
|
4195
|
-
|
|
4196
|
-
for (const [key, value] of Object.entries(features)) {
|
|
4197
|
-
const badge = document.getElementById('badge-' + key);
|
|
4198
|
-
if (badge) {
|
|
4199
|
-
const enabled = value && value.enabled;
|
|
4200
|
-
badge.textContent = enabled ? 'ON' : 'OFF';
|
|
4201
|
-
badge.className = 'profile-badge ' + (enabled ? 'enabled' : 'disabled');
|
|
4202
|
-
}
|
|
4203
|
-
}
|
|
4204
|
-
const updatedEl = document.getElementById('profile-updated-at');
|
|
4205
|
-
if (updatedEl && data.profile.updated_at) {
|
|
4206
|
-
updatedEl.textContent = 'Updated: ' + new Date(data.profile.updated_at).toLocaleString();
|
|
4207
|
-
}
|
|
4208
|
-
// Cache the prompt
|
|
4565
|
+
applyProfileToUI(data.profile);
|
|
4209
4566
|
if (data.system_prompt) {
|
|
4210
4567
|
apiState.systemPrompt = data.system_prompt;
|
|
4568
|
+
updatePromptDisplay(data.system_prompt);
|
|
4211
4569
|
}
|
|
4212
4570
|
}
|
|
4213
4571
|
} catch (e) {
|
|
@@ -4215,69 +4573,476 @@ function generateDashboardHTML(options) {
|
|
|
4215
4573
|
}
|
|
4216
4574
|
}
|
|
4217
4575
|
|
|
4218
|
-
|
|
4219
|
-
const
|
|
4220
|
-
|
|
4221
|
-
const
|
|
4222
|
-
const copyBtn = document.getElementById('copy-prompt-btn');
|
|
4223
|
-
textarea.value = data.system_prompt;
|
|
4224
|
-
textarea.style.display = 'block';
|
|
4225
|
-
copyBtn.style.display = 'inline-flex';
|
|
4226
|
-
}
|
|
4227
|
-
});
|
|
4576
|
+
function applyProfileToUI(profile) {
|
|
4577
|
+
const features = profile.features;
|
|
4578
|
+
for (const [key, value] of Object.entries(features)) {
|
|
4579
|
+
const enabled = value && value.enabled;
|
|
4228
4580
|
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4235
|
-
btn.textContent = 'Copied!';
|
|
4236
|
-
setTimeout(() => { btn.textContent = original; }, 2000);
|
|
4237
|
-
} catch (err) {
|
|
4238
|
-
console.error('Copy failed:', err);
|
|
4239
|
-
}
|
|
4240
|
-
});
|
|
4581
|
+
// Update badge
|
|
4582
|
+
const badge = document.getElementById('badge-' + key);
|
|
4583
|
+
if (badge) {
|
|
4584
|
+
badge.textContent = enabled ? 'ON' : 'OFF';
|
|
4585
|
+
badge.className = 'profile-badge ' + (enabled ? 'enabled' : 'disabled');
|
|
4586
|
+
}
|
|
4241
4587
|
|
|
4242
|
-
|
|
4243
|
-
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4588
|
+
// Update toggle (without triggering change event)
|
|
4589
|
+
const toggle = document.getElementById('toggle-' + key);
|
|
4590
|
+
if (toggle && toggle.checked !== enabled) {
|
|
4591
|
+
profileToggleLock = true;
|
|
4592
|
+
toggle.checked = enabled;
|
|
4593
|
+
profileToggleLock = false;
|
|
4594
|
+
}
|
|
4248
4595
|
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
updateSHR(),
|
|
4255
|
-
updateStatus(),
|
|
4256
|
-
updateSovereigntyProfile(),
|
|
4257
|
-
]);
|
|
4596
|
+
// Update card active state
|
|
4597
|
+
const card = document.querySelector('[data-feature="' + key + '"]');
|
|
4598
|
+
if (card) {
|
|
4599
|
+
card.classList.toggle('active', enabled);
|
|
4600
|
+
}
|
|
4258
4601
|
|
|
4259
|
-
|
|
4260
|
-
|
|
4602
|
+
// Feature-specific config UI updates
|
|
4603
|
+
if (key === 'injection_detection' && value.sensitivity) {
|
|
4604
|
+
document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(btn) {
|
|
4605
|
+
btn.classList.toggle('selected', btn.getAttribute('data-sensitivity') === value.sensitivity);
|
|
4606
|
+
});
|
|
4607
|
+
}
|
|
4261
4608
|
|
|
4262
|
-
|
|
4263
|
-
|
|
4609
|
+
if (key === 'context_gating' && value.policy_id) {
|
|
4610
|
+
const sel = document.getElementById('config-context-policy');
|
|
4611
|
+
if (sel) {
|
|
4612
|
+
// Add the policy as an option if not present
|
|
4613
|
+
let found = false;
|
|
4614
|
+
for (let i = 0; i < sel.options.length; i++) {
|
|
4615
|
+
if (sel.options[i].value === value.policy_id) { found = true; break; }
|
|
4616
|
+
}
|
|
4617
|
+
if (!found) {
|
|
4618
|
+
const opt = document.createElement('option');
|
|
4619
|
+
opt.value = value.policy_id;
|
|
4620
|
+
opt.textContent = value.policy_id;
|
|
4621
|
+
sel.appendChild(opt);
|
|
4622
|
+
}
|
|
4623
|
+
sel.value = value.policy_id;
|
|
4624
|
+
}
|
|
4625
|
+
}
|
|
4626
|
+
}
|
|
4627
|
+
|
|
4628
|
+
const updatedEl = document.getElementById('profile-updated-at');
|
|
4629
|
+
if (updatedEl && profile.updated_at) {
|
|
4630
|
+
updatedEl.textContent = 'Updated: ' + new Date(profile.updated_at).toLocaleString();
|
|
4631
|
+
}
|
|
4264
4632
|
}
|
|
4265
4633
|
|
|
4266
|
-
|
|
4267
|
-
|
|
4268
|
-
|
|
4269
|
-
|
|
4270
|
-
|
|
4271
|
-
|
|
4272
|
-
|
|
4273
|
-
|
|
4274
|
-
|
|
4275
|
-
});
|
|
4634
|
+
function updatePromptDisplay(promptText) {
|
|
4635
|
+
const display = document.getElementById('prompt-display');
|
|
4636
|
+
const content = document.getElementById('system-prompt-output');
|
|
4637
|
+
const tokenCount = document.getElementById('prompt-token-count');
|
|
4638
|
+
if (!display || !content) return;
|
|
4639
|
+
|
|
4640
|
+
if (promptText) {
|
|
4641
|
+
content.textContent = promptText;
|
|
4642
|
+
// Rough token estimate: word count * 1.3
|
|
4643
|
+
const words = promptText.split(/\\s+/).filter(function(w) { return w.length > 0; }).length;
|
|
4644
|
+
const tokens = Math.round(words * 1.3);
|
|
4645
|
+
tokenCount.textContent = '~' + tokens + ' tokens';
|
|
4646
|
+
display.classList.add('visible');
|
|
4647
|
+
}
|
|
4648
|
+
}
|
|
4649
|
+
|
|
4650
|
+
// Toggle handlers
|
|
4651
|
+
async function handleToggle(feature, enabled) {
|
|
4652
|
+
if (profileToggleLock) return;
|
|
4653
|
+
const payload = {};
|
|
4654
|
+
payload[feature] = { enabled: enabled };
|
|
4655
|
+
|
|
4656
|
+
try {
|
|
4657
|
+
const response = await fetch(API_BASE + '/api/sovereignty-profile', {
|
|
4658
|
+
method: 'POST',
|
|
4659
|
+
headers: {
|
|
4660
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
4661
|
+
'Content-Type': 'application/json',
|
|
4662
|
+
},
|
|
4663
|
+
body: JSON.stringify(payload),
|
|
4664
|
+
});
|
|
4665
|
+
|
|
4666
|
+
if (response.status === 401) {
|
|
4667
|
+
redirectToLogin();
|
|
4668
|
+
return;
|
|
4669
|
+
}
|
|
4670
|
+
|
|
4671
|
+
if (response.ok) {
|
|
4672
|
+
const data = await response.json();
|
|
4673
|
+
if (data.profile) {
|
|
4674
|
+
applyProfileToUI(data.profile);
|
|
4675
|
+
}
|
|
4676
|
+
if (data.system_prompt) {
|
|
4677
|
+
apiState.systemPrompt = data.system_prompt;
|
|
4678
|
+
updatePromptDisplay(data.system_prompt);
|
|
4679
|
+
}
|
|
4680
|
+
} else {
|
|
4681
|
+
// Revert toggle on failure
|
|
4682
|
+
const toggle = document.getElementById('toggle-' + feature);
|
|
4683
|
+
if (toggle) {
|
|
4684
|
+
profileToggleLock = true;
|
|
4685
|
+
toggle.checked = !enabled;
|
|
4686
|
+
profileToggleLock = false;
|
|
4687
|
+
}
|
|
4688
|
+
}
|
|
4689
|
+
} catch (err) {
|
|
4690
|
+
console.error('Toggle update failed:', err);
|
|
4691
|
+
// Revert toggle
|
|
4692
|
+
const toggle = document.getElementById('toggle-' + feature);
|
|
4693
|
+
if (toggle) {
|
|
4694
|
+
profileToggleLock = true;
|
|
4695
|
+
toggle.checked = !enabled;
|
|
4696
|
+
profileToggleLock = false;
|
|
4697
|
+
}
|
|
4698
|
+
}
|
|
4699
|
+
}
|
|
4700
|
+
|
|
4701
|
+
// Wire up toggle switches
|
|
4702
|
+
document.querySelectorAll('.toggle-switch input').forEach(function(toggle) {
|
|
4703
|
+
toggle.addEventListener('change', function() {
|
|
4704
|
+
const feature = this.getAttribute('data-feature');
|
|
4705
|
+
handleToggle(feature, this.checked);
|
|
4706
|
+
});
|
|
4707
|
+
});
|
|
4708
|
+
|
|
4709
|
+
// Wire up configure buttons
|
|
4710
|
+
document.querySelectorAll('.config-btn').forEach(function(btn) {
|
|
4711
|
+
btn.addEventListener('click', function() {
|
|
4712
|
+
const feature = this.getAttribute('data-config');
|
|
4713
|
+
const panel = document.getElementById('config-' + feature);
|
|
4714
|
+
if (panel) {
|
|
4715
|
+
panel.classList.toggle('open');
|
|
4716
|
+
this.textContent = panel.classList.contains('open') ? 'Close' : 'Configure';
|
|
4717
|
+
}
|
|
4718
|
+
});
|
|
4719
|
+
});
|
|
4720
|
+
|
|
4721
|
+
// Injection sensitivity handler
|
|
4722
|
+
document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(btn) {
|
|
4723
|
+
btn.addEventListener('click', async function() {
|
|
4724
|
+
const sensitivity = this.getAttribute('data-sensitivity');
|
|
4725
|
+
const response = await fetch(API_BASE + '/api/sovereignty-profile', {
|
|
4726
|
+
method: 'POST',
|
|
4727
|
+
headers: {
|
|
4728
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
4729
|
+
'Content-Type': 'application/json',
|
|
4730
|
+
},
|
|
4731
|
+
body: JSON.stringify({ injection_detection: { sensitivity: sensitivity } }),
|
|
4732
|
+
});
|
|
4733
|
+
if (response.ok) {
|
|
4734
|
+
document.querySelectorAll('#config-injection_detection .sensitivity-option').forEach(function(b) {
|
|
4735
|
+
b.classList.toggle('selected', b.getAttribute('data-sensitivity') === sensitivity);
|
|
4736
|
+
});
|
|
4737
|
+
const data = await response.json();
|
|
4738
|
+
if (data.profile) applyProfileToUI(data.profile);
|
|
4739
|
+
if (data.system_prompt) {
|
|
4740
|
+
apiState.systemPrompt = data.system_prompt;
|
|
4741
|
+
updatePromptDisplay(data.system_prompt);
|
|
4742
|
+
}
|
|
4743
|
+
}
|
|
4744
|
+
});
|
|
4745
|
+
});
|
|
4746
|
+
|
|
4747
|
+
// Context gating policy selector handler
|
|
4748
|
+
document.getElementById('config-context-policy').addEventListener('change', async function() {
|
|
4749
|
+
const policyId = this.value;
|
|
4750
|
+
const response = await fetch(API_BASE + '/api/sovereignty-profile', {
|
|
4751
|
+
method: 'POST',
|
|
4752
|
+
headers: {
|
|
4753
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
4754
|
+
'Content-Type': 'application/json',
|
|
4755
|
+
},
|
|
4756
|
+
body: JSON.stringify({ context_gating: { policy_id: policyId } }),
|
|
4757
|
+
});
|
|
4758
|
+
if (response.ok) {
|
|
4759
|
+
const data = await response.json();
|
|
4760
|
+
if (data.profile) applyProfileToUI(data.profile);
|
|
4761
|
+
if (data.system_prompt) {
|
|
4762
|
+
apiState.systemPrompt = data.system_prompt;
|
|
4763
|
+
updatePromptDisplay(data.system_prompt);
|
|
4764
|
+
}
|
|
4765
|
+
}
|
|
4766
|
+
});
|
|
4767
|
+
|
|
4768
|
+
// Generate prompt button
|
|
4769
|
+
document.getElementById('generate-prompt-btn').addEventListener('click', async () => {
|
|
4770
|
+
const data = await fetchAPI('/api/sovereignty-profile');
|
|
4771
|
+
if (data && data.system_prompt) {
|
|
4772
|
+
apiState.systemPrompt = data.system_prompt;
|
|
4773
|
+
updatePromptDisplay(data.system_prompt);
|
|
4774
|
+
}
|
|
4775
|
+
});
|
|
4776
|
+
|
|
4777
|
+
// Copy prompt button
|
|
4778
|
+
document.getElementById('copy-prompt-btn').addEventListener('click', async () => {
|
|
4779
|
+
const content = document.getElementById('system-prompt-output');
|
|
4780
|
+
if (!content || !content.textContent) return;
|
|
4781
|
+
try {
|
|
4782
|
+
await navigator.clipboard.writeText(content.textContent);
|
|
4783
|
+
const btn = document.getElementById('copy-prompt-btn');
|
|
4784
|
+
const original = btn.textContent;
|
|
4785
|
+
btn.textContent = 'Copied!';
|
|
4786
|
+
setTimeout(() => { btn.textContent = original; }, 2000);
|
|
4787
|
+
} catch (err) {
|
|
4788
|
+
console.error('Copy failed:', err);
|
|
4789
|
+
}
|
|
4790
|
+
});
|
|
4791
|
+
|
|
4792
|
+
// \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
|
|
4793
|
+
|
|
4794
|
+
let proxyServers = [];
|
|
4795
|
+
|
|
4796
|
+
async function loadProxyServers() {
|
|
4797
|
+
try {
|
|
4798
|
+
const resp = await fetch(API_BASE + '/api/proxy/servers', {
|
|
4799
|
+
headers: { 'Authorization': 'Bearer ' + AUTH_TOKEN },
|
|
4800
|
+
});
|
|
4801
|
+
if (!resp.ok) return;
|
|
4802
|
+
const data = await resp.json();
|
|
4803
|
+
proxyServers = data.servers || [];
|
|
4804
|
+
renderProxyServers();
|
|
4805
|
+
} catch (err) {
|
|
4806
|
+
// Proxy endpoint may not be available
|
|
4807
|
+
}
|
|
4808
|
+
}
|
|
4809
|
+
|
|
4810
|
+
function renderProxyServers() {
|
|
4811
|
+
const container = document.getElementById('proxy-servers-list');
|
|
4812
|
+
if (!container) return;
|
|
4813
|
+
|
|
4814
|
+
if (proxyServers.length === 0) {
|
|
4815
|
+
container.innerHTML = '<div class="empty-state">No upstream servers configured</div>';
|
|
4816
|
+
return;
|
|
4817
|
+
}
|
|
4818
|
+
|
|
4819
|
+
container.innerHTML = proxyServers.map(server => {
|
|
4820
|
+
const stateColor = server.state === 'connected' ? 'var(--green)' :
|
|
4821
|
+
server.state === 'connecting' ? 'var(--amber)' : 'var(--red)';
|
|
4822
|
+
const stateLabel = server.state || 'disconnected';
|
|
4823
|
+
const tierLabel = 'Tier ' + server.default_tier;
|
|
4824
|
+
|
|
4825
|
+
return \`
|
|
4826
|
+
<div class="proxy-server-card" data-server="\${esc(server.name)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border);">
|
|
4827
|
+
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
|
|
4828
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
4829
|
+
<span style="color: \${stateColor}; font-size: 10px;">\\u25CF</span>
|
|
4830
|
+
<span style="font-weight: 600; font-size: 14px;">\${esc(server.name)}</span>
|
|
4831
|
+
<span style="font-size: 11px; color: var(--text-secondary); background: var(--bg); padding: 2px 6px; border-radius: 3px;">\${esc(server.transport_type)}</span>
|
|
4832
|
+
</div>
|
|
4833
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
4834
|
+
<span style="font-size: 11px; color: var(--text-secondary);">\${server.tool_count} tools</span>
|
|
4835
|
+
<span style="font-size: 11px; color: var(--blue); background: rgba(88,166,255,0.1); padding: 2px 6px; border-radius: 3px;">\${tierLabel}</span>
|
|
4836
|
+
<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>
|
|
4837
|
+
</div>
|
|
4838
|
+
</div>
|
|
4839
|
+
<div style="font-size: 11px; color: var(--text-secondary);">
|
|
4840
|
+
Status: <span style="color: \${stateColor}">\${esc(stateLabel)}</span>
|
|
4841
|
+
\${server.error ? '<span style="color: var(--red);"> \u2014 ' + esc(server.error) + '</span>' : ''}
|
|
4842
|
+
</div>
|
|
4843
|
+
<div class="proxy-tools-expand" style="margin-top: 8px; display: none;">
|
|
4844
|
+
<div style="font-size: 11px; color: var(--text-secondary); margin-bottom: 4px;">Discovered Tools:</div>
|
|
4845
|
+
<div class="proxy-tools-list" style="font-size: 11px; font-family: monospace; color: var(--text-primary); max-height: 150px; overflow-y: auto;"></div>
|
|
4846
|
+
</div>
|
|
4847
|
+
</div>
|
|
4848
|
+
\`;
|
|
4849
|
+
}).join('');
|
|
4850
|
+
|
|
4851
|
+
// Attach remove handlers
|
|
4852
|
+
container.querySelectorAll('.proxy-remove-btn').forEach(btn => {
|
|
4853
|
+
btn.addEventListener('click', (e) => {
|
|
4854
|
+
const serverName = e.target.dataset.server;
|
|
4855
|
+
removeProxyServer(serverName);
|
|
4856
|
+
});
|
|
4857
|
+
});
|
|
4858
|
+
|
|
4859
|
+
// Attach expand/collapse on card click
|
|
4860
|
+
container.querySelectorAll('.proxy-server-card').forEach(card => {
|
|
4861
|
+
card.style.cursor = 'pointer';
|
|
4862
|
+
card.addEventListener('click', (e) => {
|
|
4863
|
+
if (e.target.classList.contains('proxy-remove-btn')) return;
|
|
4864
|
+
const expand = card.querySelector('.proxy-tools-expand');
|
|
4865
|
+
if (expand) {
|
|
4866
|
+
expand.style.display = expand.style.display === 'none' ? 'block' : 'none';
|
|
4867
|
+
}
|
|
4868
|
+
});
|
|
4869
|
+
});
|
|
4870
|
+
}
|
|
4871
|
+
|
|
4872
|
+
function updateProxyServerStatus(serverName, state, toolCount, error) {
|
|
4873
|
+
const server = proxyServers.find(s => s.name === serverName);
|
|
4874
|
+
if (server) {
|
|
4875
|
+
server.state = state;
|
|
4876
|
+
server.tool_count = toolCount;
|
|
4877
|
+
server.error = error;
|
|
4878
|
+
renderProxyServers();
|
|
4879
|
+
}
|
|
4880
|
+
}
|
|
4881
|
+
|
|
4882
|
+
async function addProxyServer(serverConfig) {
|
|
4883
|
+
const current = [...proxyServers];
|
|
4884
|
+
// Check for duplicate
|
|
4885
|
+
if (current.find(s => s.name === serverConfig.name)) {
|
|
4886
|
+
alert('A server with that name already exists');
|
|
4887
|
+
return;
|
|
4888
|
+
}
|
|
4889
|
+
current.push(serverConfig);
|
|
4890
|
+
|
|
4891
|
+
try {
|
|
4892
|
+
const resp = await fetch(API_BASE + '/api/proxy/servers', {
|
|
4893
|
+
method: 'POST',
|
|
4894
|
+
headers: {
|
|
4895
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
4896
|
+
'Content-Type': 'application/json',
|
|
4897
|
+
},
|
|
4898
|
+
body: JSON.stringify({ upstream_servers: current }),
|
|
4899
|
+
});
|
|
4900
|
+
if (!resp.ok) {
|
|
4901
|
+
const err = await resp.json();
|
|
4902
|
+
alert('Failed to add server: ' + (err.error || 'Unknown error'));
|
|
4903
|
+
return;
|
|
4904
|
+
}
|
|
4905
|
+
await loadProxyServers();
|
|
4906
|
+
} catch (err) {
|
|
4907
|
+
alert('Failed to add server: ' + err.message);
|
|
4908
|
+
}
|
|
4909
|
+
}
|
|
4910
|
+
|
|
4911
|
+
async function removeProxyServer(serverName) {
|
|
4912
|
+
if (!confirm('Remove upstream server "' + serverName + '"?')) return;
|
|
4913
|
+
|
|
4914
|
+
const updated = proxyServers.filter(s => s.name !== serverName);
|
|
4915
|
+
|
|
4916
|
+
try {
|
|
4917
|
+
const resp = await fetch(API_BASE + '/api/proxy/servers', {
|
|
4918
|
+
method: 'POST',
|
|
4919
|
+
headers: {
|
|
4920
|
+
'Authorization': 'Bearer ' + AUTH_TOKEN,
|
|
4921
|
+
'Content-Type': 'application/json',
|
|
4922
|
+
},
|
|
4923
|
+
body: JSON.stringify({ upstream_servers: updated }),
|
|
4924
|
+
});
|
|
4925
|
+
if (!resp.ok) {
|
|
4926
|
+
const err = await resp.json();
|
|
4927
|
+
alert('Failed to remove server: ' + (err.error || 'Unknown error'));
|
|
4928
|
+
return;
|
|
4929
|
+
}
|
|
4930
|
+
await loadProxyServers();
|
|
4931
|
+
} catch (err) {
|
|
4932
|
+
alert('Failed to remove server: ' + err.message);
|
|
4933
|
+
}
|
|
4934
|
+
}
|
|
4935
|
+
|
|
4936
|
+
// Add Server form handlers
|
|
4937
|
+
(function setupProxyForm() {
|
|
4938
|
+
const addBtn = document.getElementById('add-proxy-server-btn');
|
|
4939
|
+
const form = document.getElementById('add-server-form');
|
|
4940
|
+
const saveBtn = document.getElementById('save-server-btn');
|
|
4941
|
+
const cancelBtn = document.getElementById('cancel-server-btn');
|
|
4942
|
+
const transportSelect = document.getElementById('new-server-transport');
|
|
4943
|
+
const stdioFields = document.getElementById('stdio-fields');
|
|
4944
|
+
const sseFields = document.getElementById('sse-fields');
|
|
4945
|
+
|
|
4946
|
+
if (!addBtn || !form) return;
|
|
4947
|
+
|
|
4948
|
+
addBtn.addEventListener('click', () => {
|
|
4949
|
+
form.style.display = form.style.display === 'none' ? 'block' : 'none';
|
|
4950
|
+
});
|
|
4951
|
+
|
|
4952
|
+
cancelBtn.addEventListener('click', () => {
|
|
4953
|
+
form.style.display = 'none';
|
|
4954
|
+
});
|
|
4955
|
+
|
|
4956
|
+
transportSelect.addEventListener('change', () => {
|
|
4957
|
+
if (transportSelect.value === 'stdio') {
|
|
4958
|
+
stdioFields.style.display = 'block';
|
|
4959
|
+
sseFields.style.display = 'none';
|
|
4960
|
+
} else {
|
|
4961
|
+
stdioFields.style.display = 'none';
|
|
4962
|
+
sseFields.style.display = 'block';
|
|
4963
|
+
}
|
|
4964
|
+
});
|
|
4965
|
+
|
|
4966
|
+
saveBtn.addEventListener('click', () => {
|
|
4967
|
+
const name = document.getElementById('new-server-name').value.trim();
|
|
4968
|
+
const type = transportSelect.value;
|
|
4969
|
+
const tier = parseInt(document.getElementById('new-server-tier').value, 10);
|
|
4970
|
+
|
|
4971
|
+
if (!name) { alert('Server name is required'); return; }
|
|
4972
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(name)) { alert('Name must contain only letters, numbers, hyphens, and underscores'); return; }
|
|
4973
|
+
|
|
4974
|
+
const transport = { type };
|
|
4975
|
+
if (type === 'stdio') {
|
|
4976
|
+
const command = document.getElementById('new-server-command').value.trim();
|
|
4977
|
+
if (!command) { alert('Command is required for stdio transport'); return; }
|
|
4978
|
+
transport.command = command;
|
|
4979
|
+
const argsStr = document.getElementById('new-server-args').value.trim();
|
|
4980
|
+
if (argsStr) {
|
|
4981
|
+
transport.args = argsStr.split(',').map(s => s.trim()).filter(Boolean);
|
|
4982
|
+
}
|
|
4983
|
+
} else {
|
|
4984
|
+
const url = document.getElementById('new-server-url').value.trim();
|
|
4985
|
+
if (!url) { alert('URL is required for SSE transport'); return; }
|
|
4986
|
+
transport.url = url;
|
|
4987
|
+
}
|
|
4988
|
+
|
|
4989
|
+
addProxyServer({
|
|
4990
|
+
name,
|
|
4991
|
+
transport,
|
|
4992
|
+
enabled: true,
|
|
4993
|
+
default_tier: tier,
|
|
4994
|
+
});
|
|
4995
|
+
|
|
4996
|
+
// Reset form
|
|
4997
|
+
form.style.display = 'none';
|
|
4998
|
+
document.getElementById('new-server-name').value = '';
|
|
4999
|
+
document.getElementById('new-server-command').value = '';
|
|
5000
|
+
document.getElementById('new-server-args').value = '';
|
|
5001
|
+
document.getElementById('new-server-url').value = '';
|
|
5002
|
+
});
|
|
5003
|
+
})();
|
|
5004
|
+
|
|
5005
|
+
// Initialize
|
|
5006
|
+
async function initialize() {
|
|
5007
|
+
if (!AUTH_TOKEN) {
|
|
5008
|
+
redirectToLogin();
|
|
5009
|
+
return;
|
|
5010
|
+
}
|
|
5011
|
+
|
|
5012
|
+
// Initial data fetch
|
|
5013
|
+
await Promise.all([
|
|
5014
|
+
updateSovereignty(),
|
|
5015
|
+
updateIdentity(),
|
|
5016
|
+
updateHandshakes(),
|
|
5017
|
+
updateSHR(),
|
|
5018
|
+
updateStatus(),
|
|
5019
|
+
updateSovereigntyProfile(),
|
|
5020
|
+
loadProxyServers(),
|
|
5021
|
+
]);
|
|
5022
|
+
|
|
5023
|
+
// Setup SSE for real-time updates
|
|
5024
|
+
setupSSE();
|
|
5025
|
+
|
|
5026
|
+
// Refresh status periodically
|
|
5027
|
+
setInterval(updateStatus, 30000);
|
|
5028
|
+
}
|
|
5029
|
+
|
|
5030
|
+
// Start
|
|
5031
|
+
initialize();
|
|
5032
|
+
</script>
|
|
5033
|
+
</body>
|
|
5034
|
+
</html>`;
|
|
5035
|
+
}
|
|
5036
|
+
var init_dashboard_html = __esm({
|
|
5037
|
+
"src/principal-policy/dashboard-html.ts"() {
|
|
5038
|
+
}
|
|
5039
|
+
});
|
|
4276
5040
|
|
|
4277
5041
|
// src/system-prompt-generator.ts
|
|
4278
5042
|
function generateSystemPrompt(profile) {
|
|
4279
5043
|
const activeFeatures = [];
|
|
4280
5044
|
const inactiveFeatures = [];
|
|
5045
|
+
const activeKeys = [];
|
|
4281
5046
|
const featureKeys = [
|
|
4282
5047
|
"audit_logging",
|
|
4283
5048
|
"injection_detection",
|
|
@@ -4289,6 +5054,7 @@ function generateSystemPrompt(profile) {
|
|
|
4289
5054
|
const featureConfig = profile.features[key];
|
|
4290
5055
|
const info = FEATURE_INFO[key];
|
|
4291
5056
|
if (featureConfig.enabled) {
|
|
5057
|
+
activeKeys.push(key);
|
|
4292
5058
|
let desc = `- ${info.name}: ${info.activeDescription}`;
|
|
4293
5059
|
if (key === "injection_detection" && "sensitivity" in featureConfig && featureConfig.sensitivity) {
|
|
4294
5060
|
desc += ` Sensitivity: ${featureConfig.sensitivity}.`;
|
|
@@ -4301,14 +5067,25 @@ function generateSystemPrompt(profile) {
|
|
|
4301
5067
|
inactiveFeatures.push(info.disabledDescription);
|
|
4302
5068
|
}
|
|
4303
5069
|
}
|
|
4304
|
-
const lines = [
|
|
4305
|
-
|
|
4306
|
-
""
|
|
4307
|
-
|
|
5070
|
+
const lines = [];
|
|
5071
|
+
if (activeKeys.length > 0) {
|
|
5072
|
+
lines.push("QUICK START:");
|
|
5073
|
+
const quickStartItems = buildQuickStart(activeKeys);
|
|
5074
|
+
for (const item of quickStartItems) {
|
|
5075
|
+
lines.push(` ${item}`);
|
|
5076
|
+
}
|
|
5077
|
+
lines.push("");
|
|
5078
|
+
}
|
|
5079
|
+
lines.push(
|
|
5080
|
+
"You are protected by Sanctuary sovereignty infrastructure. The following protections are active:"
|
|
5081
|
+
);
|
|
5082
|
+
lines.push("");
|
|
4308
5083
|
if (activeFeatures.length > 0) {
|
|
4309
5084
|
lines.push(...activeFeatures);
|
|
4310
5085
|
} else {
|
|
4311
|
-
lines.push(
|
|
5086
|
+
lines.push(
|
|
5087
|
+
"- No features are currently enabled. Contact your operator to configure protections."
|
|
5088
|
+
);
|
|
4312
5089
|
}
|
|
4313
5090
|
if (inactiveFeatures.length > 0) {
|
|
4314
5091
|
lines.push("");
|
|
@@ -4318,36 +5095,82 @@ function generateSystemPrompt(profile) {
|
|
|
4318
5095
|
}
|
|
4319
5096
|
return lines.join("\n");
|
|
4320
5097
|
}
|
|
5098
|
+
function buildQuickStart(activeKeys) {
|
|
5099
|
+
const items = [];
|
|
5100
|
+
if (activeKeys.includes("context_gating")) {
|
|
5101
|
+
items.push(
|
|
5102
|
+
"1. ALWAYS call sanctuary/context_gate_filter before sending context to external APIs."
|
|
5103
|
+
);
|
|
5104
|
+
}
|
|
5105
|
+
if (activeKeys.includes("zk_proofs")) {
|
|
5106
|
+
items.push(
|
|
5107
|
+
`${items.length + 1}. Use sanctuary/zk_commit to prove claims without revealing underlying data.`
|
|
5108
|
+
);
|
|
5109
|
+
}
|
|
5110
|
+
if (activeKeys.includes("approval_gate")) {
|
|
5111
|
+
items.push(
|
|
5112
|
+
`${items.length + 1}. High-risk operations will be held for human approval \u2014 expect async responses.`
|
|
5113
|
+
);
|
|
5114
|
+
}
|
|
5115
|
+
if (items.length === 0) {
|
|
5116
|
+
if (activeKeys.includes("audit_logging")) {
|
|
5117
|
+
items.push("1. All tool calls are automatically logged to an encrypted audit trail.");
|
|
5118
|
+
}
|
|
5119
|
+
if (activeKeys.includes("injection_detection")) {
|
|
5120
|
+
items.push(
|
|
5121
|
+
`${items.length + 1}. Tool arguments are scanned for injection \u2014 blocked calls should not be retried.`
|
|
5122
|
+
);
|
|
5123
|
+
}
|
|
5124
|
+
}
|
|
5125
|
+
return items;
|
|
5126
|
+
}
|
|
4321
5127
|
var FEATURE_INFO;
|
|
4322
5128
|
var init_system_prompt_generator = __esm({
|
|
4323
5129
|
"src/system-prompt-generator.ts"() {
|
|
4324
5130
|
FEATURE_INFO = {
|
|
4325
5131
|
audit_logging: {
|
|
4326
5132
|
name: "Audit Logging",
|
|
4327
|
-
activeDescription: "All your tool calls are logged to an encrypted audit trail. No action needed \u2014 this is automatic.",
|
|
4328
|
-
|
|
5133
|
+
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.",
|
|
5134
|
+
toolNames: ["sanctuary/monitor_audit_log"],
|
|
5135
|
+
disabledDescription: "audit logging (sanctuary/monitor_audit_log)",
|
|
5136
|
+
usageExample: "Automatic \u2014 every tool call you make is recorded. No explicit action required."
|
|
4329
5137
|
},
|
|
4330
5138
|
injection_detection: {
|
|
4331
5139
|
name: "Injection Detection",
|
|
4332
|
-
activeDescription: "Your tool call arguments are scanned for prompt injection attempts.
|
|
4333
|
-
disabledDescription: "injection detection"
|
|
5140
|
+
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.",
|
|
5141
|
+
disabledDescription: "injection detection",
|
|
5142
|
+
usageExample: "Automatic \u2014 if a tool call is blocked with an injection alert, do not retry with the same arguments."
|
|
4334
5143
|
},
|
|
4335
5144
|
context_gating: {
|
|
4336
5145
|
name: "Context Gating",
|
|
4337
|
-
activeDescription: "Before
|
|
4338
|
-
toolNames: [
|
|
4339
|
-
|
|
5146
|
+
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.",
|
|
5147
|
+
toolNames: [
|
|
5148
|
+
"sanctuary/context_gate_filter",
|
|
5149
|
+
"sanctuary/context_gate_set_policy",
|
|
5150
|
+
"sanctuary/context_gate_apply_template",
|
|
5151
|
+
"sanctuary/context_gate_recommend",
|
|
5152
|
+
"sanctuary/context_gate_list_policies"
|
|
5153
|
+
],
|
|
5154
|
+
disabledDescription: "context gating (sanctuary/context_gate_filter)",
|
|
5155
|
+
usageExample: "Before calling an external API, run: sanctuary/context_gate_filter with your context object and policy_id to get a filtered version."
|
|
4340
5156
|
},
|
|
4341
5157
|
approval_gate: {
|
|
4342
5158
|
name: "Approval Gates",
|
|
4343
|
-
activeDescription: "High-risk operations require human approval before execution. Tier 1 operations always require approval
|
|
4344
|
-
disabledDescription: "approval gates"
|
|
5159
|
+
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.",
|
|
5160
|
+
disabledDescription: "approval gates",
|
|
5161
|
+
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."
|
|
4345
5162
|
},
|
|
4346
5163
|
zk_proofs: {
|
|
4347
5164
|
name: "Zero-Knowledge Proofs",
|
|
4348
|
-
activeDescription: "You can prove claims about your data without revealing the underlying values. Use sanctuary/zk_commit to create
|
|
4349
|
-
toolNames: [
|
|
4350
|
-
|
|
5165
|
+
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.",
|
|
5166
|
+
toolNames: [
|
|
5167
|
+
"sanctuary/zk_commit",
|
|
5168
|
+
"sanctuary/zk_prove",
|
|
5169
|
+
"sanctuary/zk_range_prove",
|
|
5170
|
+
"sanctuary/proof_commitment"
|
|
5171
|
+
],
|
|
5172
|
+
disabledDescription: "zero-knowledge proofs (sanctuary/zk_commit, sanctuary/zk_prove)",
|
|
5173
|
+
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."
|
|
4351
5174
|
}
|
|
4352
5175
|
};
|
|
4353
5176
|
}
|
|
@@ -4379,6 +5202,7 @@ var init_dashboard = __esm({
|
|
|
4379
5202
|
shrOpts = null;
|
|
4380
5203
|
_sanctuaryConfig = null;
|
|
4381
5204
|
profileStore = null;
|
|
5205
|
+
clientManager = null;
|
|
4382
5206
|
dashboardHTML;
|
|
4383
5207
|
loginHTML;
|
|
4384
5208
|
authToken;
|
|
@@ -4400,8 +5224,7 @@ var init_dashboard = __esm({
|
|
|
4400
5224
|
this.sessionTTLMs = isLocalhost ? SESSION_TTL_LOCAL_MS : SESSION_TTL_REMOTE_MS;
|
|
4401
5225
|
this.dashboardHTML = generateDashboardHTML({
|
|
4402
5226
|
timeoutSeconds: config.timeout_seconds,
|
|
4403
|
-
serverVersion: SANCTUARY_VERSION
|
|
4404
|
-
authToken: this.authToken
|
|
5227
|
+
serverVersion: SANCTUARY_VERSION
|
|
4405
5228
|
});
|
|
4406
5229
|
this.loginHTML = generateLoginHTML({ serverVersion: SANCTUARY_VERSION });
|
|
4407
5230
|
this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
|
|
@@ -4419,6 +5242,7 @@ var init_dashboard = __esm({
|
|
|
4419
5242
|
if (deps.shrOpts) this.shrOpts = deps.shrOpts;
|
|
4420
5243
|
if (deps.sanctuaryConfig) this._sanctuaryConfig = deps.sanctuaryConfig;
|
|
4421
5244
|
if (deps.profileStore) this.profileStore = deps.profileStore;
|
|
5245
|
+
if (deps.clientManager) this.clientManager = deps.clientManager;
|
|
4422
5246
|
}
|
|
4423
5247
|
/**
|
|
4424
5248
|
* Mark this dashboard as running in standalone mode.
|
|
@@ -4770,6 +5594,10 @@ var init_dashboard = __esm({
|
|
|
4770
5594
|
this.handleSovereigntyProfileGet(res);
|
|
4771
5595
|
} else if (method === "POST" && url.pathname === "/api/sovereignty-profile") {
|
|
4772
5596
|
this.handleSovereigntyProfileUpdate(req, res);
|
|
5597
|
+
} else if (method === "GET" && url.pathname === "/api/proxy/servers") {
|
|
5598
|
+
this.handleProxyServers(res);
|
|
5599
|
+
} else if (method === "POST" && url.pathname === "/api/proxy/servers") {
|
|
5600
|
+
this.handleProxyServersUpdate(req, res);
|
|
4773
5601
|
} else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
|
|
4774
5602
|
if (!this.checkRateLimit(req, res, "decisions")) return;
|
|
4775
5603
|
const id = url.pathname.slice("/api/approve/".length);
|
|
@@ -5116,6 +5944,85 @@ data: ${JSON.stringify(initData)}
|
|
|
5116
5944
|
}
|
|
5117
5945
|
});
|
|
5118
5946
|
}
|
|
5947
|
+
// ── Proxy Server Handlers ───────────────────────────────────────────
|
|
5948
|
+
/**
|
|
5949
|
+
* GET /api/proxy/servers — list upstream proxy servers and their status.
|
|
5950
|
+
*/
|
|
5951
|
+
handleProxyServers(res) {
|
|
5952
|
+
const profile = this.profileStore?.get();
|
|
5953
|
+
const upstreamServers = profile?.upstream_servers ?? [];
|
|
5954
|
+
const clientStatus = this.clientManager?.getStatus() ?? [];
|
|
5955
|
+
const servers = upstreamServers.map((server) => {
|
|
5956
|
+
const status = clientStatus.find((s) => s.name === server.name);
|
|
5957
|
+
return {
|
|
5958
|
+
name: server.name,
|
|
5959
|
+
transport_type: server.transport.type,
|
|
5960
|
+
enabled: server.enabled,
|
|
5961
|
+
default_tier: server.default_tier,
|
|
5962
|
+
state: status?.state ?? "disconnected",
|
|
5963
|
+
tool_count: status?.tool_count ?? 0,
|
|
5964
|
+
error: status?.error,
|
|
5965
|
+
tool_overrides: server.tool_overrides ?? {}
|
|
5966
|
+
};
|
|
5967
|
+
});
|
|
5968
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
5969
|
+
res.end(JSON.stringify({ servers }));
|
|
5970
|
+
}
|
|
5971
|
+
/**
|
|
5972
|
+
* POST /api/proxy/servers — update upstream server configuration.
|
|
5973
|
+
* This is a dashboard action (human-initiated), so it's allowed with audit logging
|
|
5974
|
+
* rather than requiring Tier 1 approval.
|
|
5975
|
+
*/
|
|
5976
|
+
handleProxyServersUpdate(req, res) {
|
|
5977
|
+
if (!this.profileStore) {
|
|
5978
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
5979
|
+
res.end(JSON.stringify({ error: "Profile store not available" }));
|
|
5980
|
+
return;
|
|
5981
|
+
}
|
|
5982
|
+
let body = "";
|
|
5983
|
+
let destroyed = false;
|
|
5984
|
+
req.on("data", (chunk) => {
|
|
5985
|
+
body += chunk.toString();
|
|
5986
|
+
if (body.length > 16384) {
|
|
5987
|
+
destroyed = true;
|
|
5988
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
5989
|
+
res.end(JSON.stringify({ error: "Request body too large" }));
|
|
5990
|
+
req.destroy();
|
|
5991
|
+
}
|
|
5992
|
+
});
|
|
5993
|
+
req.on("end", async () => {
|
|
5994
|
+
if (destroyed) return;
|
|
5995
|
+
try {
|
|
5996
|
+
const { upstream_servers } = JSON.parse(body);
|
|
5997
|
+
const updated = await this.profileStore.update({ upstream_servers });
|
|
5998
|
+
if (this.auditLog) {
|
|
5999
|
+
this.auditLog.append("l2", "proxy_servers_update_dashboard", "dashboard", {
|
|
6000
|
+
server_count: upstream_servers.length,
|
|
6001
|
+
servers: upstream_servers.map((s) => ({
|
|
6002
|
+
name: s.name,
|
|
6003
|
+
type: s.transport.type,
|
|
6004
|
+
enabled: s.enabled,
|
|
6005
|
+
tier: s.default_tier
|
|
6006
|
+
}))
|
|
6007
|
+
});
|
|
6008
|
+
}
|
|
6009
|
+
if (this.clientManager && updated.upstream_servers) {
|
|
6010
|
+
this.clientManager.configure(updated.upstream_servers).catch(() => {
|
|
6011
|
+
});
|
|
6012
|
+
}
|
|
6013
|
+
this.broadcastSSE("proxy-servers-update", {
|
|
6014
|
+
servers: updated.upstream_servers ?? [],
|
|
6015
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
6016
|
+
});
|
|
6017
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
6018
|
+
res.end(JSON.stringify({ upstream_servers: updated.upstream_servers ?? [] }));
|
|
6019
|
+
} catch (err) {
|
|
6020
|
+
const message = err instanceof Error ? err.message : "Invalid request";
|
|
6021
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
6022
|
+
res.end(JSON.stringify({ error: message }));
|
|
6023
|
+
}
|
|
6024
|
+
});
|
|
6025
|
+
}
|
|
5119
6026
|
// ── SSE Broadcasting ────────────────────────────────────────────────
|
|
5120
6027
|
broadcastSSE(event, data) {
|
|
5121
6028
|
const message = `event: ${event}
|
|
@@ -5226,7 +6133,8 @@ function createDefaultProfile() {
|
|
|
5226
6133
|
audit_logging: { enabled: true },
|
|
5227
6134
|
injection_detection: { enabled: true },
|
|
5228
6135
|
context_gating: { enabled: false },
|
|
5229
|
-
approval_gate: { enabled:
|
|
6136
|
+
approval_gate: { enabled: true },
|
|
6137
|
+
// SEC-057: always enabled — core enforcement
|
|
5230
6138
|
zk_proofs: { enabled: false }
|
|
5231
6139
|
},
|
|
5232
6140
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -5286,6 +6194,9 @@ var init_sovereignty_profile = __esm({
|
|
|
5286
6194
|
if (!this.profile) {
|
|
5287
6195
|
await this.load();
|
|
5288
6196
|
}
|
|
6197
|
+
if (updates.approval_gate && updates.approval_gate.enabled === false) {
|
|
6198
|
+
throw new Error("approval_gate cannot be disabled \u2014 it is a core enforcement feature");
|
|
6199
|
+
}
|
|
5289
6200
|
const features = this.profile.features;
|
|
5290
6201
|
if (updates.audit_logging !== void 0) {
|
|
5291
6202
|
if (updates.audit_logging.enabled !== void 0) {
|
|
@@ -5340,6 +6251,48 @@ var init_sovereignty_profile = __esm({
|
|
|
5340
6251
|
features.zk_proofs.enabled = updates.zk_proofs.enabled;
|
|
5341
6252
|
}
|
|
5342
6253
|
}
|
|
6254
|
+
if (updates.upstream_servers !== void 0) {
|
|
6255
|
+
if (!Array.isArray(updates.upstream_servers)) {
|
|
6256
|
+
throw new Error("upstream_servers must be an array");
|
|
6257
|
+
}
|
|
6258
|
+
for (const server of updates.upstream_servers) {
|
|
6259
|
+
if (!server.name || typeof server.name !== "string") {
|
|
6260
|
+
throw new Error("Each upstream server must have a name");
|
|
6261
|
+
}
|
|
6262
|
+
if (server.name.length > 128) {
|
|
6263
|
+
throw new Error("Upstream server name must be 128 characters or fewer");
|
|
6264
|
+
}
|
|
6265
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(server.name)) {
|
|
6266
|
+
throw new Error("Upstream server name must contain only alphanumeric characters, hyphens, and underscores");
|
|
6267
|
+
}
|
|
6268
|
+
if (!server.transport || typeof server.transport !== "object") {
|
|
6269
|
+
throw new Error("Each upstream server must have a transport configuration");
|
|
6270
|
+
}
|
|
6271
|
+
if (server.transport.type !== "stdio" && server.transport.type !== "sse") {
|
|
6272
|
+
throw new Error("Transport type must be 'stdio' or 'sse'");
|
|
6273
|
+
}
|
|
6274
|
+
if (server.transport.type === "stdio" && !server.transport.command) {
|
|
6275
|
+
throw new Error("stdio transport requires a command");
|
|
6276
|
+
}
|
|
6277
|
+
if (server.transport.type === "sse" && !server.transport.url) {
|
|
6278
|
+
throw new Error("sse transport requires a url");
|
|
6279
|
+
}
|
|
6280
|
+
if (typeof server.enabled !== "boolean") {
|
|
6281
|
+
throw new Error("Each upstream server must have enabled as a boolean");
|
|
6282
|
+
}
|
|
6283
|
+
if (![1, 2, 3].includes(server.default_tier)) {
|
|
6284
|
+
throw new Error("default_tier must be 1, 2, or 3");
|
|
6285
|
+
}
|
|
6286
|
+
if (server.tool_overrides) {
|
|
6287
|
+
for (const [, override] of Object.entries(server.tool_overrides)) {
|
|
6288
|
+
if (![1, 2, 3].includes(override.tier)) {
|
|
6289
|
+
throw new Error("tool_overrides tier must be 1, 2, or 3");
|
|
6290
|
+
}
|
|
6291
|
+
}
|
|
6292
|
+
}
|
|
6293
|
+
}
|
|
6294
|
+
this.profile.upstream_servers = updates.upstream_servers;
|
|
6295
|
+
}
|
|
5343
6296
|
this.profile.updated_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
5344
6297
|
await this.persist();
|
|
5345
6298
|
return this.profile;
|
|
@@ -8142,6 +9095,70 @@ var TOOL_INVOCATION_PATTERNS = [
|
|
|
8142
9095
|
];
|
|
8143
9096
|
var URL_PATTERN = /https?:\/\/[^\s"'<>]+/i;
|
|
8144
9097
|
var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
|
|
9098
|
+
var INVISIBLE_CHARS = [
|
|
9099
|
+
"\u200B",
|
|
9100
|
+
// Zero-width space
|
|
9101
|
+
"\u200C",
|
|
9102
|
+
// Zero-width non-joiner
|
|
9103
|
+
"\u200D",
|
|
9104
|
+
// Zero-width joiner
|
|
9105
|
+
"\uFEFF",
|
|
9106
|
+
// Zero-width no-break space (BOM)
|
|
9107
|
+
"\xAD",
|
|
9108
|
+
// Soft hyphen
|
|
9109
|
+
"\u200E",
|
|
9110
|
+
// Left-to-right mark
|
|
9111
|
+
"\u200F",
|
|
9112
|
+
// Right-to-left mark
|
|
9113
|
+
"\u2060",
|
|
9114
|
+
// Word joiner
|
|
9115
|
+
"\u2061",
|
|
9116
|
+
// Function application
|
|
9117
|
+
"\u2062",
|
|
9118
|
+
// Invisible times
|
|
9119
|
+
"\u2063",
|
|
9120
|
+
// Invisible separator
|
|
9121
|
+
"\u2064",
|
|
9122
|
+
// Invisible plus
|
|
9123
|
+
"\u180E",
|
|
9124
|
+
// Mongolian vowel separator
|
|
9125
|
+
"\u034F",
|
|
9126
|
+
// Combining grapheme joiner
|
|
9127
|
+
"\u061C",
|
|
9128
|
+
// Arabic letter mark
|
|
9129
|
+
"\u115F",
|
|
9130
|
+
// Hangul choseong filler
|
|
9131
|
+
"\u1160",
|
|
9132
|
+
// Hangul jungseong filler
|
|
9133
|
+
"\u17B4",
|
|
9134
|
+
// Khmer vowel inherent AQ
|
|
9135
|
+
"\u17B5",
|
|
9136
|
+
// Khmer vowel inherent AA
|
|
9137
|
+
"\u3164",
|
|
9138
|
+
// Hangul filler
|
|
9139
|
+
"\uFFA0",
|
|
9140
|
+
// Halfwidth hangul filler
|
|
9141
|
+
"\u202A",
|
|
9142
|
+
// Left-to-Right Embedding (LRE)
|
|
9143
|
+
"\u202B",
|
|
9144
|
+
// Right-to-Left Embedding (RLE)
|
|
9145
|
+
"\u202C",
|
|
9146
|
+
// Pop Directional Formatting (PDF)
|
|
9147
|
+
"\u202D",
|
|
9148
|
+
// Left-to-Right Override (LRO)
|
|
9149
|
+
"\u202E",
|
|
9150
|
+
// Right-to-Left Override (RLO)
|
|
9151
|
+
"\u2066",
|
|
9152
|
+
// Left-to-Right Isolate (LRI)
|
|
9153
|
+
"\u2067",
|
|
9154
|
+
// Right-to-Left Isolate (RLI)
|
|
9155
|
+
"\u2068",
|
|
9156
|
+
// First Strong Isolate (FSI)
|
|
9157
|
+
"\u2069"
|
|
9158
|
+
// Pop Directional Isolate (PDI)
|
|
9159
|
+
];
|
|
9160
|
+
var VARIATION_SELECTOR_RANGE_START = 65024;
|
|
9161
|
+
var VARIATION_SELECTOR_RANGE_END = 65039;
|
|
8145
9162
|
var ZERO_WIDTH_CHARS = [
|
|
8146
9163
|
"\u200B",
|
|
8147
9164
|
// Zero-width space
|
|
@@ -8152,6 +9169,66 @@ var ZERO_WIDTH_CHARS = [
|
|
|
8152
9169
|
"\uFEFF"
|
|
8153
9170
|
// Zero-width no-break space
|
|
8154
9171
|
];
|
|
9172
|
+
var BASE64_STANDARD_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
9173
|
+
var BASE64URL_PATTERN = /^[A-Za-z0-9_-]+={0,2}$/;
|
|
9174
|
+
var BASE64_BLOCK_PATTERN = /[A-Za-z0-9+/]{20,}={0,2}/g;
|
|
9175
|
+
var HEX_ENCODED_PATTERN = /(?:0x)?[0-9a-fA-F]{20,}/g;
|
|
9176
|
+
var HTML_ENTITY_PATTERN = /&#(?:x[0-9a-fA-F]{2,4}|[0-9]{2,5});/g;
|
|
9177
|
+
var URL_ENCODED_PATTERN = /(?:%[0-9a-fA-F]{2}){4,}/g;
|
|
9178
|
+
var SECRET_PATTERNS = [
|
|
9179
|
+
{ pattern: /sk-[a-zA-Z0-9]{20,}/, name: "openai_api_key" },
|
|
9180
|
+
{ pattern: /sk-ant-[a-zA-Z0-9_-]{20,}/, name: "anthropic_api_key" },
|
|
9181
|
+
{ pattern: /ghp_[a-zA-Z0-9]{36,}/, name: "github_pat" },
|
|
9182
|
+
{ pattern: /gho_[a-zA-Z0-9]{36,}/, name: "github_oauth" },
|
|
9183
|
+
{ pattern: /ghs_[a-zA-Z0-9]{36,}/, name: "github_app" },
|
|
9184
|
+
{ pattern: /github_pat_[a-zA-Z0-9_]{22,}/, name: "github_fine_grained_pat" },
|
|
9185
|
+
{ pattern: /AKIA[0-9A-Z]{16}/, name: "aws_access_key" },
|
|
9186
|
+
{ pattern: /xoxb-[0-9]{10,}-[a-zA-Z0-9-]+/, name: "slack_bot_token" },
|
|
9187
|
+
{ pattern: /xoxp-[0-9]{10,}-[a-zA-Z0-9-]+/, name: "slack_user_token" },
|
|
9188
|
+
{ pattern: /xapp-[0-9]-[A-Z0-9]+-[0-9]+-[a-z0-9]+/, name: "slack_app_token" },
|
|
9189
|
+
{ pattern: /(?:Bearer|bearer)\s+[a-zA-Z0-9._~+/=-]{20,}/, name: "bearer_token" },
|
|
9190
|
+
{ pattern: /glpat-[a-zA-Z0-9_-]{20,}/, name: "gitlab_pat" },
|
|
9191
|
+
{ pattern: /npm_[a-zA-Z0-9]{36,}/, name: "npm_token" },
|
|
9192
|
+
{ pattern: /pypi-[a-zA-Z0-9_-]{20,}/, name: "pypi_token" },
|
|
9193
|
+
{ pattern: /AIza[a-zA-Z0-9_-]{35}/, name: "google_api_key" },
|
|
9194
|
+
{ pattern: /SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}/, name: "sendgrid_api_key" },
|
|
9195
|
+
{ pattern: /sq0[a-z]{3}-[a-zA-Z0-9_-]{22,}/, name: "square_api_key" },
|
|
9196
|
+
{ pattern: /sk_live_[a-zA-Z0-9]{24,}/, name: "stripe_secret_key" },
|
|
9197
|
+
{ pattern: /rk_live_[a-zA-Z0-9]{24,}/, name: "stripe_restricted_key" },
|
|
9198
|
+
{ pattern: /(?:-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----)/, name: "private_key_pem" }
|
|
9199
|
+
];
|
|
9200
|
+
var MARKDOWN_IMAGE_EXFIL_PATTERN = /!\[[^\]]*\]\(https?:\/\/[^)]*[?&](?:data|secret|key|token|password|auth|session|cookie|api_key|access_token)=/i;
|
|
9201
|
+
var INTERNAL_PATH_PATTERNS = [
|
|
9202
|
+
/\/home\/[a-zA-Z0-9_.-]+\//,
|
|
9203
|
+
/\/Users\/[a-zA-Z0-9_.-]+\//,
|
|
9204
|
+
/[A-Z]:\\(?:Users|Documents|Program Files)\\/,
|
|
9205
|
+
/~\/\.(?:ssh|aws|config|gnupg|sanctuary)\//,
|
|
9206
|
+
/\/etc\/(?:passwd|shadow|hosts|ssh)/,
|
|
9207
|
+
/\/var\/(?:log|run|lib)\//
|
|
9208
|
+
];
|
|
9209
|
+
var PRIVATE_NETWORK_PATTERNS = [
|
|
9210
|
+
/(?:^|\s|\/\/)(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3})/,
|
|
9211
|
+
/(?:^|\s|\/\/)(?:172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})/,
|
|
9212
|
+
/(?:^|\s|\/\/)(?:192\.168\.\d{1,3}\.\d{1,3})/,
|
|
9213
|
+
/(?:^|\s|\/\/)localhost(?::\d+)?/,
|
|
9214
|
+
/(?:^|\s|\/\/)127\.0\.0\.1/,
|
|
9215
|
+
/(?:^|\s|\/\/)0\.0\.0\.0/,
|
|
9216
|
+
/(?:^|\s|\/\/)\[?::1\]?/
|
|
9217
|
+
];
|
|
9218
|
+
var OUTPUT_ROLE_MARKER_PATTERNS = [
|
|
9219
|
+
/\bsystem\s*:/i,
|
|
9220
|
+
/\[INST\]/,
|
|
9221
|
+
/\[\/INST\]/,
|
|
9222
|
+
/<\|im_start\|>/,
|
|
9223
|
+
/<\|im_end\|>/,
|
|
9224
|
+
/<\|system\|>/,
|
|
9225
|
+
/<\|user\|>/,
|
|
9226
|
+
/<\|assistant\|>/,
|
|
9227
|
+
/<<\s*SYS\s*>>/,
|
|
9228
|
+
/<<\s*\/SYS\s*>>/,
|
|
9229
|
+
/\[SYSTEM\]/,
|
|
9230
|
+
/### (?:System|Human|Assistant):/
|
|
9231
|
+
];
|
|
8155
9232
|
var InjectionDetector = class {
|
|
8156
9233
|
config;
|
|
8157
9234
|
stats = {
|
|
@@ -8208,6 +9285,50 @@ var InjectionDetector = class {
|
|
|
8208
9285
|
recommendation
|
|
8209
9286
|
};
|
|
8210
9287
|
}
|
|
9288
|
+
/**
|
|
9289
|
+
* SEC-035: Scan outbound content for secret leaks, data exfiltration,
|
|
9290
|
+
* internal path exposure, and injection artifact survival.
|
|
9291
|
+
*
|
|
9292
|
+
* @param content The outbound content string to scan
|
|
9293
|
+
* @returns DetectionResult with outbound-specific signal types
|
|
9294
|
+
*/
|
|
9295
|
+
scanOutbound(content) {
|
|
9296
|
+
this.stats.total_scans++;
|
|
9297
|
+
if (!this.config.enabled) {
|
|
9298
|
+
return {
|
|
9299
|
+
flagged: false,
|
|
9300
|
+
confidence: 0,
|
|
9301
|
+
signals: [],
|
|
9302
|
+
recommendation: "allow"
|
|
9303
|
+
};
|
|
9304
|
+
}
|
|
9305
|
+
const signals = [];
|
|
9306
|
+
this.detectSecretPatterns(content, signals);
|
|
9307
|
+
this.detectOutboundExfiltration(content, signals);
|
|
9308
|
+
this.detectInternalPathLeaks(content, signals);
|
|
9309
|
+
this.detectPrivateNetworkLeaks(content, signals);
|
|
9310
|
+
this.detectOutputRoleMarkers(content, signals);
|
|
9311
|
+
const flagged = signals.length > 0;
|
|
9312
|
+
if (flagged) {
|
|
9313
|
+
this.stats.total_flags++;
|
|
9314
|
+
}
|
|
9315
|
+
for (const sig of signals) {
|
|
9316
|
+
this.stats.signals_by_type[sig.type] = (this.stats.signals_by_type[sig.type] ?? 0) + 1;
|
|
9317
|
+
}
|
|
9318
|
+
const recommendation = this.computeRecommendation(
|
|
9319
|
+
signals,
|
|
9320
|
+
this.config.sensitivity
|
|
9321
|
+
);
|
|
9322
|
+
if (recommendation === "block") {
|
|
9323
|
+
this.stats.total_blocks++;
|
|
9324
|
+
}
|
|
9325
|
+
return {
|
|
9326
|
+
flagged,
|
|
9327
|
+
confidence: this.computeConfidence(signals),
|
|
9328
|
+
signals,
|
|
9329
|
+
recommendation
|
|
9330
|
+
};
|
|
9331
|
+
}
|
|
8211
9332
|
/**
|
|
8212
9333
|
* Recursively scan a value and all nested values.
|
|
8213
9334
|
*/
|
|
@@ -8236,14 +9357,40 @@ var InjectionDetector = class {
|
|
|
8236
9357
|
return;
|
|
8237
9358
|
}
|
|
8238
9359
|
const location = path || "root";
|
|
8239
|
-
const
|
|
8240
|
-
if (
|
|
9360
|
+
const invisibleCount = this.countInvisibleChars(value);
|
|
9361
|
+
if (invisibleCount > 3) {
|
|
9362
|
+
signals.push({
|
|
9363
|
+
type: "unicode_smuggling",
|
|
9364
|
+
pattern: `invisible_chars_count_${invisibleCount}`,
|
|
9365
|
+
location,
|
|
9366
|
+
severity: "high"
|
|
9367
|
+
});
|
|
9368
|
+
}
|
|
9369
|
+
this.detectTokenBudgetAttack(value, location, signals);
|
|
9370
|
+
const stripped = this.stripInvisibleChars(value);
|
|
9371
|
+
const nfkcOnly = stripped.normalize("NFKC");
|
|
9372
|
+
const normalized = this.normalizeConfusables(nfkcOnly);
|
|
9373
|
+
if (nfkcOnly !== stripped) {
|
|
9374
|
+
signals.push({
|
|
9375
|
+
type: "encoding_evasion",
|
|
9376
|
+
pattern: "unicode_normalization_delta",
|
|
9377
|
+
location,
|
|
9378
|
+
severity: "medium"
|
|
9379
|
+
});
|
|
9380
|
+
}
|
|
9381
|
+
if (normalized !== nfkcOnly) {
|
|
8241
9382
|
signals.push({
|
|
8242
9383
|
type: "encoding_evasion",
|
|
8243
9384
|
pattern: "unicode_normalization_delta",
|
|
8244
9385
|
location,
|
|
8245
9386
|
severity: "medium"
|
|
8246
9387
|
});
|
|
9388
|
+
signals.push({
|
|
9389
|
+
type: "homoglyph_attack",
|
|
9390
|
+
pattern: "confusable_substitution",
|
|
9391
|
+
location,
|
|
9392
|
+
severity: "high"
|
|
9393
|
+
});
|
|
8247
9394
|
}
|
|
8248
9395
|
for (const pattern of ROLE_OVERRIDE_PATTERNS) {
|
|
8249
9396
|
if (pattern.test(normalized)) {
|
|
@@ -8281,21 +9428,363 @@ var InjectionDetector = class {
|
|
|
8281
9428
|
}
|
|
8282
9429
|
}
|
|
8283
9430
|
this.detectEncodingEvasion(value, location, signals);
|
|
9431
|
+
this.detectEncodedPayloads(value, location, signals);
|
|
8284
9432
|
this.detectDataExfiltration(value, location, signals);
|
|
8285
9433
|
this.detectPromptStuffing(value, location, signals);
|
|
8286
9434
|
}
|
|
9435
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9436
|
+
// SEC-034: Unicode sanitization helpers
|
|
9437
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
8287
9438
|
/**
|
|
8288
|
-
*
|
|
9439
|
+
* Count invisible Unicode characters in a string.
|
|
9440
|
+
* Includes zero-width chars, soft hyphens, directional marks,
|
|
9441
|
+
* variation selectors, and other invisible categories.
|
|
8289
9442
|
*/
|
|
8290
|
-
|
|
8291
|
-
|
|
9443
|
+
countInvisibleChars(value) {
|
|
9444
|
+
let count = 0;
|
|
9445
|
+
for (const ch of value) {
|
|
9446
|
+
const cp = ch.codePointAt(0);
|
|
9447
|
+
if (cp === void 0) continue;
|
|
9448
|
+
if (INVISIBLE_CHARS.includes(ch)) {
|
|
9449
|
+
count++;
|
|
9450
|
+
continue;
|
|
9451
|
+
}
|
|
9452
|
+
if (cp >= VARIATION_SELECTOR_RANGE_START && cp <= VARIATION_SELECTOR_RANGE_END) {
|
|
9453
|
+
count++;
|
|
9454
|
+
continue;
|
|
9455
|
+
}
|
|
9456
|
+
if (cp >= 917760 && cp <= 917999) {
|
|
9457
|
+
count++;
|
|
9458
|
+
continue;
|
|
9459
|
+
}
|
|
9460
|
+
if (cp >= 917505 && cp <= 917631) {
|
|
9461
|
+
count++;
|
|
9462
|
+
continue;
|
|
9463
|
+
}
|
|
9464
|
+
if (cp >= 65529 && cp <= 65531) {
|
|
9465
|
+
count++;
|
|
9466
|
+
continue;
|
|
9467
|
+
}
|
|
9468
|
+
}
|
|
9469
|
+
return count;
|
|
9470
|
+
}
|
|
9471
|
+
/**
|
|
9472
|
+
* Strip invisible characters from a string for clean pattern matching.
|
|
9473
|
+
* Returns a new string with all invisible chars removed.
|
|
9474
|
+
*/
|
|
9475
|
+
stripInvisibleChars(value) {
|
|
9476
|
+
const chars = [];
|
|
9477
|
+
for (const ch of value) {
|
|
9478
|
+
const cp = ch.codePointAt(0);
|
|
9479
|
+
if (cp === void 0) continue;
|
|
9480
|
+
if (INVISIBLE_CHARS.includes(ch)) continue;
|
|
9481
|
+
if (cp >= VARIATION_SELECTOR_RANGE_START && cp <= VARIATION_SELECTOR_RANGE_END) continue;
|
|
9482
|
+
if (cp >= 917760 && cp <= 917999) continue;
|
|
9483
|
+
if (cp >= 917505 && cp <= 917631) continue;
|
|
9484
|
+
if (cp >= 65529 && cp <= 65531) continue;
|
|
9485
|
+
chars.push(ch);
|
|
9486
|
+
}
|
|
9487
|
+
return chars.join("");
|
|
9488
|
+
}
|
|
9489
|
+
/**
|
|
9490
|
+
* SEC-034: Token budget attack detection.
|
|
9491
|
+
* Some Unicode sequences expand dramatically during tokenization (e.g., CJK
|
|
9492
|
+
* ideographs, combining characters, emoji sequences). If the estimated token
|
|
9493
|
+
* cost per character is anomalously high, this may be a wallet-drain payload.
|
|
9494
|
+
*
|
|
9495
|
+
* Heuristic: count chars that typically tokenize into multiple tokens.
|
|
9496
|
+
* If the ratio of estimated tokens to char count exceeds 3x, flag it.
|
|
9497
|
+
*/
|
|
9498
|
+
detectTokenBudgetAttack(value, path, signals) {
|
|
9499
|
+
if (value.length < 20) return;
|
|
9500
|
+
const MAX_ANALYSIS_LENGTH = 1e6;
|
|
9501
|
+
if (value.length > MAX_ANALYSIS_LENGTH) {
|
|
9502
|
+
value = value.substring(0, MAX_ANALYSIS_LENGTH);
|
|
9503
|
+
}
|
|
9504
|
+
let estimatedTokens = 0;
|
|
9505
|
+
for (const ch of value) {
|
|
9506
|
+
const cp = ch.codePointAt(0);
|
|
9507
|
+
if (cp === void 0) continue;
|
|
9508
|
+
if (cp <= 127) {
|
|
9509
|
+
estimatedTokens += 0.25;
|
|
9510
|
+
} else if (cp <= 2047) {
|
|
9511
|
+
estimatedTokens += 0.5;
|
|
9512
|
+
} else if (cp <= 65535) {
|
|
9513
|
+
estimatedTokens += 1.5;
|
|
9514
|
+
} else {
|
|
9515
|
+
estimatedTokens += 2.5;
|
|
9516
|
+
}
|
|
9517
|
+
}
|
|
9518
|
+
let charCount = 0;
|
|
9519
|
+
for (const _ch of value) {
|
|
9520
|
+
charCount++;
|
|
9521
|
+
}
|
|
9522
|
+
const ratio = estimatedTokens / charCount;
|
|
9523
|
+
if (ratio > 3) {
|
|
8292
9524
|
signals.push({
|
|
8293
|
-
type: "
|
|
8294
|
-
pattern:
|
|
8295
|
-
location: path
|
|
9525
|
+
type: "token_budget_attack",
|
|
9526
|
+
pattern: `token_char_ratio_${ratio.toFixed(2)}`,
|
|
9527
|
+
location: path,
|
|
8296
9528
|
severity: "medium"
|
|
8297
9529
|
});
|
|
8298
9530
|
}
|
|
9531
|
+
}
|
|
9532
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9533
|
+
// SEC-034: Encoded payload detection and re-scanning
|
|
9534
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9535
|
+
/**
|
|
9536
|
+
* Detect encoded content (base64, hex, HTML entities, URL encoding),
|
|
9537
|
+
* decode it, and re-scan the decoded content through injection patterns.
|
|
9538
|
+
* If the decoded content contains injection patterns, flag as encoding_evasion.
|
|
9539
|
+
*/
|
|
9540
|
+
detectEncodedPayloads(value, path, signals) {
|
|
9541
|
+
const decodedParts = [];
|
|
9542
|
+
const base64Matches = value.match(BASE64_BLOCK_PATTERN);
|
|
9543
|
+
if (base64Matches) {
|
|
9544
|
+
for (const match of base64Matches) {
|
|
9545
|
+
const decoded = this.safeBase64Decode(match);
|
|
9546
|
+
if (decoded !== null) {
|
|
9547
|
+
decodedParts.push(decoded);
|
|
9548
|
+
}
|
|
9549
|
+
}
|
|
9550
|
+
}
|
|
9551
|
+
const hexMatches = value.match(HEX_ENCODED_PATTERN);
|
|
9552
|
+
if (hexMatches) {
|
|
9553
|
+
for (const match of hexMatches) {
|
|
9554
|
+
const decoded = this.safeHexDecode(match);
|
|
9555
|
+
if (decoded !== null) {
|
|
9556
|
+
decodedParts.push(decoded);
|
|
9557
|
+
}
|
|
9558
|
+
}
|
|
9559
|
+
}
|
|
9560
|
+
if (HTML_ENTITY_PATTERN.test(value)) {
|
|
9561
|
+
const decoded = this.decodeHtmlEntities(value);
|
|
9562
|
+
if (decoded !== value) {
|
|
9563
|
+
decodedParts.push(decoded);
|
|
9564
|
+
}
|
|
9565
|
+
}
|
|
9566
|
+
const urlMatches = value.match(URL_ENCODED_PATTERN);
|
|
9567
|
+
if (urlMatches) {
|
|
9568
|
+
for (const match of urlMatches) {
|
|
9569
|
+
const decoded = this.safeUrlDecode(match);
|
|
9570
|
+
if (decoded !== null && decoded !== match) {
|
|
9571
|
+
decodedParts.push(decoded);
|
|
9572
|
+
}
|
|
9573
|
+
}
|
|
9574
|
+
}
|
|
9575
|
+
for (const decoded of decodedParts) {
|
|
9576
|
+
if (this.containsInjectionPatterns(decoded)) {
|
|
9577
|
+
signals.push({
|
|
9578
|
+
type: "encoding_evasion",
|
|
9579
|
+
pattern: "encoded_injection_payload",
|
|
9580
|
+
location: path,
|
|
9581
|
+
severity: "high"
|
|
9582
|
+
});
|
|
9583
|
+
return;
|
|
9584
|
+
}
|
|
9585
|
+
}
|
|
9586
|
+
}
|
|
9587
|
+
/**
|
|
9588
|
+
* Check if a string contains any injection patterns (role override or security bypass).
|
|
9589
|
+
*/
|
|
9590
|
+
containsInjectionPatterns(value) {
|
|
9591
|
+
const normalized = this.normalizeConfusables(value.normalize("NFKC"));
|
|
9592
|
+
for (const pattern of ROLE_OVERRIDE_PATTERNS) {
|
|
9593
|
+
if (pattern.test(normalized)) return true;
|
|
9594
|
+
}
|
|
9595
|
+
for (const pattern of SECURITY_BYPASS_PATTERNS) {
|
|
9596
|
+
if (pattern.test(normalized)) return true;
|
|
9597
|
+
}
|
|
9598
|
+
return false;
|
|
9599
|
+
}
|
|
9600
|
+
/**
|
|
9601
|
+
* Safely decode a base64 string. Returns null if it's not valid base64
|
|
9602
|
+
* or doesn't decode to a meaningful string.
|
|
9603
|
+
*/
|
|
9604
|
+
safeBase64Decode(value) {
|
|
9605
|
+
try {
|
|
9606
|
+
const cleaned = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
9607
|
+
const padded = cleaned + "=".repeat((4 - cleaned.length % 4) % 4);
|
|
9608
|
+
if (!BASE64_STANDARD_PATTERN.test(padded)) return null;
|
|
9609
|
+
const decoded = Buffer.from(padded, "base64").toString("utf-8");
|
|
9610
|
+
if (this.looksLikeText(decoded)) {
|
|
9611
|
+
return decoded;
|
|
9612
|
+
}
|
|
9613
|
+
return null;
|
|
9614
|
+
} catch {
|
|
9615
|
+
return null;
|
|
9616
|
+
}
|
|
9617
|
+
}
|
|
9618
|
+
/**
|
|
9619
|
+
* Safely decode a hex string. Returns null on failure.
|
|
9620
|
+
*/
|
|
9621
|
+
safeHexDecode(value) {
|
|
9622
|
+
try {
|
|
9623
|
+
const hex = value.startsWith("0x") ? value.slice(2) : value;
|
|
9624
|
+
if (hex.length % 2 !== 0) return null;
|
|
9625
|
+
const decoded = Buffer.from(hex, "hex").toString("utf-8");
|
|
9626
|
+
if (this.looksLikeText(decoded)) {
|
|
9627
|
+
return decoded;
|
|
9628
|
+
}
|
|
9629
|
+
return null;
|
|
9630
|
+
} catch {
|
|
9631
|
+
return null;
|
|
9632
|
+
}
|
|
9633
|
+
}
|
|
9634
|
+
/**
|
|
9635
|
+
* Decode HTML numeric entities (&#xHH; and &#DDD;) in a string.
|
|
9636
|
+
*/
|
|
9637
|
+
decodeHtmlEntities(value) {
|
|
9638
|
+
return value.replace(/&#x([0-9a-fA-F]{2,4});/g, (_match, hex) => {
|
|
9639
|
+
try {
|
|
9640
|
+
return String.fromCodePoint(parseInt(hex, 16));
|
|
9641
|
+
} catch {
|
|
9642
|
+
return _match;
|
|
9643
|
+
}
|
|
9644
|
+
}).replace(/&#([0-9]{2,5});/g, (_match, dec) => {
|
|
9645
|
+
try {
|
|
9646
|
+
const cp = parseInt(dec, 10);
|
|
9647
|
+
if (cp > 1114111) return _match;
|
|
9648
|
+
return String.fromCodePoint(cp);
|
|
9649
|
+
} catch {
|
|
9650
|
+
return _match;
|
|
9651
|
+
}
|
|
9652
|
+
});
|
|
9653
|
+
}
|
|
9654
|
+
/**
|
|
9655
|
+
* Safely decode a URL-encoded string. Returns null on failure.
|
|
9656
|
+
*/
|
|
9657
|
+
safeUrlDecode(value) {
|
|
9658
|
+
try {
|
|
9659
|
+
return decodeURIComponent(value);
|
|
9660
|
+
} catch {
|
|
9661
|
+
return null;
|
|
9662
|
+
}
|
|
9663
|
+
}
|
|
9664
|
+
/**
|
|
9665
|
+
* Heuristic: does this look like readable text (vs. binary garbage)?
|
|
9666
|
+
* Checks that most characters are printable ASCII or common Unicode.
|
|
9667
|
+
*/
|
|
9668
|
+
looksLikeText(value) {
|
|
9669
|
+
if (value.length === 0) return false;
|
|
9670
|
+
let printable = 0;
|
|
9671
|
+
for (let i = 0; i < value.length; i++) {
|
|
9672
|
+
const code = value.charCodeAt(i);
|
|
9673
|
+
if (code >= 32 && code <= 126 || code === 10 || code === 13 || code === 9) {
|
|
9674
|
+
printable++;
|
|
9675
|
+
} else if (code >= 128) {
|
|
9676
|
+
if (code < 160) continue;
|
|
9677
|
+
printable++;
|
|
9678
|
+
}
|
|
9679
|
+
}
|
|
9680
|
+
return printable / value.length > 0.7;
|
|
9681
|
+
}
|
|
9682
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9683
|
+
// SEC-035: Outbound content scanning helpers
|
|
9684
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9685
|
+
/**
|
|
9686
|
+
* Detect API keys and secrets in outbound content.
|
|
9687
|
+
*/
|
|
9688
|
+
detectSecretPatterns(content, signals) {
|
|
9689
|
+
for (const { pattern, name } of SECRET_PATTERNS) {
|
|
9690
|
+
if (pattern.test(content)) {
|
|
9691
|
+
signals.push({
|
|
9692
|
+
type: "secret_leak",
|
|
9693
|
+
pattern: name,
|
|
9694
|
+
location: "outbound",
|
|
9695
|
+
severity: "high"
|
|
9696
|
+
});
|
|
9697
|
+
}
|
|
9698
|
+
}
|
|
9699
|
+
}
|
|
9700
|
+
/**
|
|
9701
|
+
* Detect data exfiltration via markdown images with data-carrying query params.
|
|
9702
|
+
*/
|
|
9703
|
+
detectOutboundExfiltration(content, signals) {
|
|
9704
|
+
if (MARKDOWN_IMAGE_EXFIL_PATTERN.test(content)) {
|
|
9705
|
+
signals.push({
|
|
9706
|
+
type: "data_exfiltration",
|
|
9707
|
+
pattern: "markdown_image_exfil",
|
|
9708
|
+
location: "outbound",
|
|
9709
|
+
severity: "high"
|
|
9710
|
+
});
|
|
9711
|
+
}
|
|
9712
|
+
}
|
|
9713
|
+
/**
|
|
9714
|
+
* Detect internal filesystem path leaks in outbound content.
|
|
9715
|
+
*/
|
|
9716
|
+
detectInternalPathLeaks(content, signals) {
|
|
9717
|
+
for (const pattern of INTERNAL_PATH_PATTERNS) {
|
|
9718
|
+
if (pattern.test(content)) {
|
|
9719
|
+
signals.push({
|
|
9720
|
+
type: "internal_path_leak",
|
|
9721
|
+
pattern: pattern.source,
|
|
9722
|
+
location: "outbound",
|
|
9723
|
+
severity: "medium"
|
|
9724
|
+
});
|
|
9725
|
+
return;
|
|
9726
|
+
}
|
|
9727
|
+
}
|
|
9728
|
+
}
|
|
9729
|
+
/**
|
|
9730
|
+
* Detect private IP addresses and localhost references in outbound content.
|
|
9731
|
+
*/
|
|
9732
|
+
detectPrivateNetworkLeaks(content, signals) {
|
|
9733
|
+
for (const pattern of PRIVATE_NETWORK_PATTERNS) {
|
|
9734
|
+
if (pattern.test(content)) {
|
|
9735
|
+
signals.push({
|
|
9736
|
+
type: "private_network_leak",
|
|
9737
|
+
pattern: pattern.source,
|
|
9738
|
+
location: "outbound",
|
|
9739
|
+
severity: "medium"
|
|
9740
|
+
});
|
|
9741
|
+
return;
|
|
9742
|
+
}
|
|
9743
|
+
}
|
|
9744
|
+
}
|
|
9745
|
+
/**
|
|
9746
|
+
* Detect role markers / prompt template artifacts in outbound content.
|
|
9747
|
+
* These should never appear in agent output — their presence indicates
|
|
9748
|
+
* injection artifact survival.
|
|
9749
|
+
*/
|
|
9750
|
+
detectOutputRoleMarkers(content, signals) {
|
|
9751
|
+
for (const pattern of OUTPUT_ROLE_MARKER_PATTERNS) {
|
|
9752
|
+
if (pattern.test(content)) {
|
|
9753
|
+
signals.push({
|
|
9754
|
+
type: "injection_artifact",
|
|
9755
|
+
pattern: pattern.source,
|
|
9756
|
+
location: "outbound",
|
|
9757
|
+
severity: "high"
|
|
9758
|
+
});
|
|
9759
|
+
return;
|
|
9760
|
+
}
|
|
9761
|
+
}
|
|
9762
|
+
}
|
|
9763
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9764
|
+
// Existing detection methods (enhanced)
|
|
9765
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9766
|
+
/**
|
|
9767
|
+
* Detect base64 strings, base64url, and zero-width character evasion.
|
|
9768
|
+
*/
|
|
9769
|
+
detectEncodingEvasion(value, path, signals) {
|
|
9770
|
+
const trimmed = value.trim();
|
|
9771
|
+
if (value.length > 50) {
|
|
9772
|
+
if (BASE64_STANDARD_PATTERN.test(trimmed)) {
|
|
9773
|
+
signals.push({
|
|
9774
|
+
type: "encoding_evasion",
|
|
9775
|
+
pattern: "base64_string",
|
|
9776
|
+
location: path || "root",
|
|
9777
|
+
severity: "medium"
|
|
9778
|
+
});
|
|
9779
|
+
} else if (BASE64URL_PATTERN.test(trimmed) && /[_-]/.test(trimmed)) {
|
|
9780
|
+
signals.push({
|
|
9781
|
+
type: "encoding_evasion",
|
|
9782
|
+
pattern: "base64url_string",
|
|
9783
|
+
location: path || "root",
|
|
9784
|
+
severity: "medium"
|
|
9785
|
+
});
|
|
9786
|
+
}
|
|
9787
|
+
}
|
|
8299
9788
|
let zeroWidthCount = 0;
|
|
8300
9789
|
for (const char of ZERO_WIDTH_CHARS) {
|
|
8301
9790
|
zeroWidthCount += (value.match(new RegExp(char, "g")) || []).length;
|
|
@@ -8474,62 +9963,89 @@ var InjectionDetector = class {
|
|
|
8474
9963
|
return structuredFields.some((p) => p.test(path));
|
|
8475
9964
|
}
|
|
8476
9965
|
/**
|
|
8477
|
-
* SEC-032: Map common cross-script confusable characters to their
|
|
8478
|
-
* NFKC normalization handles fullwidth and compatibility
|
|
8479
|
-
* Cyrillic/Greek lookalikes to
|
|
8480
|
-
*
|
|
9966
|
+
* SEC-032/SEC-034: Map common cross-script confusable characters to their
|
|
9967
|
+
* Latin equivalents. NFKC normalization handles fullwidth and compatibility
|
|
9968
|
+
* forms, but does NOT map Cyrillic/Greek/Armenian/Georgian lookalikes to
|
|
9969
|
+
* Latin (they're distinct codepoints by design).
|
|
9970
|
+
*
|
|
9971
|
+
* Extended to 50+ confusable pairs covering Cyrillic, Greek, Armenian,
|
|
9972
|
+
* Georgian, Cherokee, and mathematical/symbol lookalikes.
|
|
8481
9973
|
*/
|
|
8482
9974
|
normalizeConfusables(value) {
|
|
8483
9975
|
const confusables = {
|
|
8484
|
-
// Cyrillic → Latin
|
|
9976
|
+
// ── Cyrillic → Latin ──────────────────────────────────────────────
|
|
8485
9977
|
"\u0410": "A",
|
|
8486
9978
|
"\u0430": "a",
|
|
8487
9979
|
// А а
|
|
8488
9980
|
"\u0412": "B",
|
|
8489
9981
|
"\u0432": "b",
|
|
8490
|
-
// В
|
|
9982
|
+
// В в (visual approximation)
|
|
8491
9983
|
"\u0421": "C",
|
|
8492
9984
|
"\u0441": "c",
|
|
8493
9985
|
// С с
|
|
9986
|
+
"\u0414": "D",
|
|
9987
|
+
// Д (visual approximation)
|
|
8494
9988
|
"\u0415": "E",
|
|
8495
9989
|
"\u0435": "e",
|
|
8496
9990
|
// Е е
|
|
8497
9991
|
"\u041D": "H",
|
|
8498
9992
|
"\u043D": "h",
|
|
8499
|
-
// Н
|
|
9993
|
+
// Н н (visual approximation)
|
|
9994
|
+
"\u0406": "I",
|
|
9995
|
+
"\u0456": "i",
|
|
9996
|
+
// І і (Ukrainian I)
|
|
9997
|
+
"\u0408": "J",
|
|
9998
|
+
// Ј (Serbian Je)
|
|
8500
9999
|
"\u041A": "K",
|
|
8501
10000
|
"\u043A": "k",
|
|
8502
|
-
// К к (
|
|
10001
|
+
// К к (visual approximation)
|
|
8503
10002
|
"\u041C": "M",
|
|
8504
10003
|
"\u043C": "m",
|
|
8505
|
-
// М
|
|
10004
|
+
// М м (visual approximation)
|
|
8506
10005
|
"\u041E": "O",
|
|
8507
10006
|
"\u043E": "o",
|
|
8508
10007
|
// О о
|
|
8509
10008
|
"\u0420": "P",
|
|
8510
10009
|
"\u0440": "p",
|
|
8511
10010
|
// Р р
|
|
10011
|
+
"\u0405": "S",
|
|
10012
|
+
"\u0455": "s",
|
|
10013
|
+
// Ѕ ѕ (Macedonian S)
|
|
8512
10014
|
"\u0422": "T",
|
|
8513
10015
|
"\u0442": "t",
|
|
8514
|
-
// Т
|
|
10016
|
+
// Т т (visual approximation)
|
|
8515
10017
|
"\u0425": "X",
|
|
8516
10018
|
"\u0445": "x",
|
|
8517
10019
|
// Х х
|
|
8518
10020
|
"\u0423": "Y",
|
|
8519
10021
|
"\u0443": "y",
|
|
8520
|
-
// У (
|
|
8521
|
-
|
|
10022
|
+
// У у (visual approximation)
|
|
10023
|
+
"\u0417": "3",
|
|
10024
|
+
// З (looks like 3)
|
|
10025
|
+
"\u04BB": "h",
|
|
10026
|
+
// һ (Shha)
|
|
10027
|
+
"\u04C0": "I",
|
|
10028
|
+
// Ӏ (Palochka)
|
|
10029
|
+
"\u04CF": "l",
|
|
10030
|
+
// ӏ (Palochka small)
|
|
10031
|
+
// ── Greek → Latin ─────────────────────────────────────────────────
|
|
8522
10032
|
"\u0391": "A",
|
|
8523
10033
|
"\u03B1": "a",
|
|
8524
|
-
// Α α (not exact)
|
|
10034
|
+
// Α α (alpha not exact)
|
|
8525
10035
|
"\u0392": "B",
|
|
8526
10036
|
"\u03B2": "b",
|
|
8527
10037
|
// Β β (not exact)
|
|
10038
|
+
"\u0393": "G",
|
|
10039
|
+
// Γ (visual approximation)
|
|
8528
10040
|
"\u0395": "E",
|
|
8529
10041
|
"\u03B5": "e",
|
|
8530
10042
|
// Ε ε (not exact)
|
|
10043
|
+
"\u0396": "Z",
|
|
10044
|
+
"\u03B6": "z",
|
|
10045
|
+
// Ζ ζ (not exact)
|
|
8531
10046
|
"\u0397": "H",
|
|
8532
|
-
|
|
10047
|
+
"\u03B7": "n",
|
|
10048
|
+
// Η η (not exact)
|
|
8533
10049
|
"\u0399": "I",
|
|
8534
10050
|
"\u03B9": "i",
|
|
8535
10051
|
// Ι ι
|
|
@@ -8553,8 +10069,78 @@ var InjectionDetector = class {
|
|
|
8553
10069
|
"\u03C5": "y",
|
|
8554
10070
|
// Υ υ (not exact)
|
|
8555
10071
|
"\u03A7": "X",
|
|
8556
|
-
"\u03C7": "x"
|
|
10072
|
+
"\u03C7": "x",
|
|
8557
10073
|
// Χ χ (not exact)
|
|
10074
|
+
"\u03C9": "w",
|
|
10075
|
+
// ω (omega, visual approximation)
|
|
10076
|
+
// ── Armenian → Latin ──────────────────────────────────────────────
|
|
10077
|
+
"\u0555": "O",
|
|
10078
|
+
// Օ
|
|
10079
|
+
"\u0585": "o",
|
|
10080
|
+
// օ
|
|
10081
|
+
"\u054D": "S",
|
|
10082
|
+
// Ս
|
|
10083
|
+
"\u057D": "s",
|
|
10084
|
+
// ս
|
|
10085
|
+
"\u054C": "L",
|
|
10086
|
+
// Լ (visual approximation)
|
|
10087
|
+
"\u0570": "h",
|
|
10088
|
+
// հ
|
|
10089
|
+
// ── Cherokee → Latin ──────────────────────────────────────────────
|
|
10090
|
+
"\u13A0": "D",
|
|
10091
|
+
// Ꭰ
|
|
10092
|
+
"\u13B3": "W",
|
|
10093
|
+
// Ꮃ
|
|
10094
|
+
"\u13A1": "R",
|
|
10095
|
+
// Ꭱ
|
|
10096
|
+
"\u13AA": "G",
|
|
10097
|
+
// Ꭺ (looks like A but maps to G sound)
|
|
10098
|
+
"\u13D2": "V",
|
|
10099
|
+
// Ꮢ (visual approximation)
|
|
10100
|
+
// ── Georgian → Latin ──────────────────────────────────────────────
|
|
10101
|
+
"\u10D5": "v",
|
|
10102
|
+
// ვ (Georgian letter vin)
|
|
10103
|
+
"\u10D3": "d",
|
|
10104
|
+
// დ (Georgian letter don)
|
|
10105
|
+
"\u10DA": "l",
|
|
10106
|
+
// ლ (Georgian letter las)
|
|
10107
|
+
// ── Latin special → Latin ────────────────────────────────────────
|
|
10108
|
+
"\u0131": "i",
|
|
10109
|
+
// ı (Latin small letter dotless i)
|
|
10110
|
+
// ── Symbols / Mathematical → Latin ────────────────────────────────
|
|
10111
|
+
// Note: NFKC normalization handles mathematical alphanumerics (U+1D400–U+1D7FF)
|
|
10112
|
+
"\u2160": "I",
|
|
10113
|
+
// Ⅰ (Roman numeral one)
|
|
10114
|
+
"\u2164": "V",
|
|
10115
|
+
// Ⅴ (Roman numeral five)
|
|
10116
|
+
"\u2169": "X",
|
|
10117
|
+
// Ⅹ (Roman numeral ten)
|
|
10118
|
+
"\u216C": "L",
|
|
10119
|
+
// Ⅼ (Roman numeral fifty)
|
|
10120
|
+
"\u216D": "C",
|
|
10121
|
+
// Ⅽ (Roman numeral one hundred)
|
|
10122
|
+
"\u216E": "D",
|
|
10123
|
+
// Ⅾ (Roman numeral five hundred)
|
|
10124
|
+
"\u216F": "M",
|
|
10125
|
+
// Ⅿ (Roman numeral one thousand)
|
|
10126
|
+
"\u2170": "i",
|
|
10127
|
+
// ⅰ (small Roman numeral one)
|
|
10128
|
+
"\u2174": "v",
|
|
10129
|
+
// ⅴ (small Roman numeral five)
|
|
10130
|
+
"\u2179": "x",
|
|
10131
|
+
// ⅹ (small Roman numeral ten)
|
|
10132
|
+
"\u217C": "l",
|
|
10133
|
+
// ⅼ (small Roman numeral fifty)
|
|
10134
|
+
"\u217D": "c",
|
|
10135
|
+
// ⅽ (small Roman numeral one hundred)
|
|
10136
|
+
"\u217E": "d",
|
|
10137
|
+
// ⅾ (small Roman numeral five hundred)
|
|
10138
|
+
"\u217F": "m",
|
|
10139
|
+
// ⅿ (small Roman numeral one thousand)
|
|
10140
|
+
"\u0251": "a",
|
|
10141
|
+
// ɑ (Latin alpha — looks like 'a')
|
|
10142
|
+
"\u0261": "g"
|
|
10143
|
+
// ɡ (Latin small letter script G)
|
|
8558
10144
|
};
|
|
8559
10145
|
let result = value;
|
|
8560
10146
|
if (/[^\x00-\x7F]/.test(value)) {
|
|
@@ -8644,6 +10230,7 @@ var ApprovalGate = class {
|
|
|
8644
10230
|
auditLog;
|
|
8645
10231
|
injectionDetector;
|
|
8646
10232
|
onInjectionAlert;
|
|
10233
|
+
proxyTierResolver;
|
|
8647
10234
|
constructor(policy, baseline, channel, auditLog, injectionDetector, onInjectionAlert) {
|
|
8648
10235
|
this.policy = policy;
|
|
8649
10236
|
this.baseline = baseline;
|
|
@@ -8652,6 +10239,12 @@ var ApprovalGate = class {
|
|
|
8652
10239
|
this.injectionDetector = injectionDetector ?? new InjectionDetector();
|
|
8653
10240
|
this.onInjectionAlert = onInjectionAlert;
|
|
8654
10241
|
}
|
|
10242
|
+
/**
|
|
10243
|
+
* Set the proxy tier resolver. Called after the proxy router is initialized.
|
|
10244
|
+
*/
|
|
10245
|
+
setProxyTierResolver(resolver) {
|
|
10246
|
+
this.proxyTierResolver = resolver;
|
|
10247
|
+
}
|
|
8655
10248
|
/**
|
|
8656
10249
|
* Evaluate a tool call against the Principal Policy.
|
|
8657
10250
|
*
|
|
@@ -8704,6 +10297,38 @@ var ApprovalGate = class {
|
|
|
8704
10297
|
);
|
|
8705
10298
|
}
|
|
8706
10299
|
}
|
|
10300
|
+
if (toolName.startsWith("proxy/") && this.proxyTierResolver) {
|
|
10301
|
+
const proxyTier = this.proxyTierResolver(toolName);
|
|
10302
|
+
if (proxyTier !== null) {
|
|
10303
|
+
if (proxyTier === 1) {
|
|
10304
|
+
return this.requestApproval(operation, 1, `Proxy tool "${toolName}" is configured as Tier 1 (always requires approval)`, {
|
|
10305
|
+
operation: toolName,
|
|
10306
|
+
proxy: true,
|
|
10307
|
+
args_summary: this.summarizeArgs(args)
|
|
10308
|
+
});
|
|
10309
|
+
}
|
|
10310
|
+
if (proxyTier === 2) {
|
|
10311
|
+
const anomaly2 = this.detectAnomaly(operation, args);
|
|
10312
|
+
if (anomaly2) {
|
|
10313
|
+
return this.requestApproval(operation, 2, `Proxy: ${anomaly2.reason}`, {
|
|
10314
|
+
...anomaly2.context,
|
|
10315
|
+
proxy: true
|
|
10316
|
+
});
|
|
10317
|
+
}
|
|
10318
|
+
}
|
|
10319
|
+
this.auditLog.append("l2", `gate_allow_proxy:${toolName}`, "system", {
|
|
10320
|
+
tier: proxyTier,
|
|
10321
|
+
operation: toolName,
|
|
10322
|
+
proxy: true
|
|
10323
|
+
});
|
|
10324
|
+
return {
|
|
10325
|
+
allowed: true,
|
|
10326
|
+
tier: proxyTier,
|
|
10327
|
+
reason: `Proxy operation allowed (Tier ${proxyTier})`,
|
|
10328
|
+
approval_required: false
|
|
10329
|
+
};
|
|
10330
|
+
}
|
|
10331
|
+
}
|
|
8707
10332
|
if (this.policy.tier1_always_approve.includes(operation)) {
|
|
8708
10333
|
return this.requestApproval(operation, 1, `"${operation}" is a Tier 1 operation (always requires approval)`, {
|
|
8709
10334
|
operation,
|
|
@@ -10403,7 +12028,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
|
|
|
10403
12028
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
10404
12029
|
const canonicalBytes = canonicalize(outcome);
|
|
10405
12030
|
const canonicalString = new TextDecoder().decode(canonicalBytes);
|
|
10406
|
-
const
|
|
12031
|
+
const sha2565 = createCommitment(canonicalString);
|
|
10407
12032
|
let pedersenData;
|
|
10408
12033
|
if (includePedersen && Number.isInteger(outcome.rounds) && outcome.rounds >= 0) {
|
|
10409
12034
|
const pedersen = createPedersenCommitment(outcome.rounds);
|
|
@@ -10415,7 +12040,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
|
|
|
10415
12040
|
const commitmentPayload = {
|
|
10416
12041
|
bridge_commitment_id: commitmentId,
|
|
10417
12042
|
session_id: outcome.session_id,
|
|
10418
|
-
sha256_commitment:
|
|
12043
|
+
sha256_commitment: sha2565.commitment,
|
|
10419
12044
|
terms_hash: outcome.terms_hash,
|
|
10420
12045
|
committer_did: identity.did,
|
|
10421
12046
|
committed_at: now,
|
|
@@ -10426,8 +12051,8 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
|
|
|
10426
12051
|
return {
|
|
10427
12052
|
bridge_commitment_id: commitmentId,
|
|
10428
12053
|
session_id: outcome.session_id,
|
|
10429
|
-
sha256_commitment:
|
|
10430
|
-
blinding_factor:
|
|
12054
|
+
sha256_commitment: sha2565.commitment,
|
|
12055
|
+
blinding_factor: sha2565.blinding_factor,
|
|
10431
12056
|
committer_did: identity.did,
|
|
10432
12057
|
signature: toBase64url(signature),
|
|
10433
12058
|
pedersen_commitment: pedersenData,
|
|
@@ -13630,22 +15255,858 @@ function createSovereigntyProfileTools(profileStore, auditLog) {
|
|
|
13630
15255
|
];
|
|
13631
15256
|
return { tools };
|
|
13632
15257
|
}
|
|
13633
|
-
|
|
13634
|
-
|
|
13635
|
-
|
|
13636
|
-
|
|
13637
|
-
|
|
13638
|
-
|
|
13639
|
-
|
|
13640
|
-
|
|
13641
|
-
|
|
13642
|
-
|
|
13643
|
-
|
|
13644
|
-
|
|
13645
|
-
|
|
13646
|
-
|
|
13647
|
-
|
|
13648
|
-
|
|
15258
|
+
var MAX_RETRIES = 5;
|
|
15259
|
+
var BASE_BACKOFF_MS = 1e3;
|
|
15260
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
15261
|
+
var MAX_UPSTREAM_SERVERS = 20;
|
|
15262
|
+
var ClientManager = class {
|
|
15263
|
+
connections = /* @__PURE__ */ new Map();
|
|
15264
|
+
onStateChange;
|
|
15265
|
+
shutdownRequested = false;
|
|
15266
|
+
constructor(options) {
|
|
15267
|
+
this.onStateChange = options?.onStateChange;
|
|
15268
|
+
}
|
|
15269
|
+
/**
|
|
15270
|
+
* Configure upstream servers. Disconnects removed servers, connects new ones.
|
|
15271
|
+
* Non-blocking — connection failures are handled asynchronously.
|
|
15272
|
+
*/
|
|
15273
|
+
async configure(servers) {
|
|
15274
|
+
if (servers.length > MAX_UPSTREAM_SERVERS) {
|
|
15275
|
+
throw new Error(`Maximum ${MAX_UPSTREAM_SERVERS} upstream servers allowed`);
|
|
15276
|
+
}
|
|
15277
|
+
const SAFE_SERVER_NAME = /^[a-zA-Z0-9_\-]+$/;
|
|
15278
|
+
const newNames = new Set(servers.filter((s) => {
|
|
15279
|
+
if (!SAFE_SERVER_NAME.test(s.name)) {
|
|
15280
|
+
return false;
|
|
15281
|
+
}
|
|
15282
|
+
return s.enabled;
|
|
15283
|
+
}).map((s) => s.name));
|
|
15284
|
+
for (const [name] of this.connections) {
|
|
15285
|
+
if (!newNames.has(name)) {
|
|
15286
|
+
await this.disconnectServer(name);
|
|
15287
|
+
}
|
|
15288
|
+
}
|
|
15289
|
+
for (const server of servers) {
|
|
15290
|
+
if (!SAFE_SERVER_NAME.test(server.name)) {
|
|
15291
|
+
continue;
|
|
15292
|
+
}
|
|
15293
|
+
if (!server.enabled) {
|
|
15294
|
+
if (this.connections.has(server.name)) {
|
|
15295
|
+
await this.disconnectServer(server.name);
|
|
15296
|
+
}
|
|
15297
|
+
continue;
|
|
15298
|
+
}
|
|
15299
|
+
const existing = this.connections.get(server.name);
|
|
15300
|
+
if (existing && existing.state === "connected") {
|
|
15301
|
+
existing.server = server;
|
|
15302
|
+
continue;
|
|
15303
|
+
}
|
|
15304
|
+
this.connectServer(server);
|
|
15305
|
+
}
|
|
15306
|
+
}
|
|
15307
|
+
/**
|
|
15308
|
+
* Get all discovered tools across all connected upstream servers.
|
|
15309
|
+
*/
|
|
15310
|
+
getAllTools() {
|
|
15311
|
+
const result = /* @__PURE__ */ new Map();
|
|
15312
|
+
for (const [name, conn] of this.connections) {
|
|
15313
|
+
if (conn.state === "connected" && conn.tools.length > 0) {
|
|
15314
|
+
result.set(name, conn.tools);
|
|
15315
|
+
}
|
|
15316
|
+
}
|
|
15317
|
+
return result;
|
|
15318
|
+
}
|
|
15319
|
+
/**
|
|
15320
|
+
* Get connection status for all configured servers.
|
|
15321
|
+
*/
|
|
15322
|
+
getStatus() {
|
|
15323
|
+
return Array.from(this.connections.values()).map((conn) => ({
|
|
15324
|
+
name: conn.server.name,
|
|
15325
|
+
state: conn.state,
|
|
15326
|
+
transport_type: conn.server.transport.type,
|
|
15327
|
+
tool_count: conn.tools.length,
|
|
15328
|
+
error: conn.error
|
|
15329
|
+
}));
|
|
15330
|
+
}
|
|
15331
|
+
/**
|
|
15332
|
+
* Get the upstream server config by name.
|
|
15333
|
+
*/
|
|
15334
|
+
getServerConfig(name) {
|
|
15335
|
+
return this.connections.get(name)?.server;
|
|
15336
|
+
}
|
|
15337
|
+
/**
|
|
15338
|
+
* Call a tool on an upstream server.
|
|
15339
|
+
*/
|
|
15340
|
+
async callTool(serverName, toolName, args) {
|
|
15341
|
+
const conn = this.connections.get(serverName);
|
|
15342
|
+
if (!conn) {
|
|
15343
|
+
throw new Error(`Upstream server "${serverName}" is not configured`);
|
|
15344
|
+
}
|
|
15345
|
+
if (conn.state !== "connected" || !conn.client) {
|
|
15346
|
+
throw new Error(`Upstream server "${serverName}" is not connected (state: ${conn.state})`);
|
|
15347
|
+
}
|
|
15348
|
+
const result = await conn.client.callTool({
|
|
15349
|
+
name: toolName,
|
|
15350
|
+
arguments: args
|
|
15351
|
+
});
|
|
15352
|
+
return result;
|
|
15353
|
+
}
|
|
15354
|
+
/**
|
|
15355
|
+
* Shut down all connections cleanly.
|
|
15356
|
+
*/
|
|
15357
|
+
async shutdown() {
|
|
15358
|
+
this.shutdownRequested = true;
|
|
15359
|
+
for (const conn of this.connections.values()) {
|
|
15360
|
+
if (conn.retryTimer) {
|
|
15361
|
+
clearTimeout(conn.retryTimer);
|
|
15362
|
+
conn.retryTimer = void 0;
|
|
15363
|
+
}
|
|
15364
|
+
}
|
|
15365
|
+
const disconnects = Array.from(this.connections.keys()).map(
|
|
15366
|
+
(name) => this.disconnectServer(name)
|
|
15367
|
+
);
|
|
15368
|
+
await Promise.allSettled(disconnects);
|
|
15369
|
+
}
|
|
15370
|
+
// ── Private ───────────────────────────────────────────────────────────
|
|
15371
|
+
/**
|
|
15372
|
+
* Connect to an upstream server (non-blocking).
|
|
15373
|
+
* Spawns connection attempt in background — does not throw.
|
|
15374
|
+
*/
|
|
15375
|
+
connectServer(server) {
|
|
15376
|
+
const conn = {
|
|
15377
|
+
server,
|
|
15378
|
+
client: null,
|
|
15379
|
+
transport: null,
|
|
15380
|
+
state: "connecting",
|
|
15381
|
+
tools: [],
|
|
15382
|
+
retryCount: 0
|
|
15383
|
+
};
|
|
15384
|
+
this.connections.set(server.name, conn);
|
|
15385
|
+
this.notifyStateChange(conn);
|
|
15386
|
+
this.doConnect(conn).catch(() => {
|
|
15387
|
+
});
|
|
15388
|
+
}
|
|
15389
|
+
/**
|
|
15390
|
+
* Perform the actual connection to an upstream server.
|
|
15391
|
+
*/
|
|
15392
|
+
async doConnect(conn) {
|
|
15393
|
+
try {
|
|
15394
|
+
conn.state = "connecting";
|
|
15395
|
+
this.notifyStateChange(conn);
|
|
15396
|
+
let transport;
|
|
15397
|
+
if (conn.server.transport.type === "stdio") {
|
|
15398
|
+
if (!conn.server.transport.command) {
|
|
15399
|
+
throw new Error("stdio transport requires a command");
|
|
15400
|
+
}
|
|
15401
|
+
if (conn.server.transport.args) {
|
|
15402
|
+
const SAFE_ARG_PATTERN = /^[a-zA-Z0-9._\-\/=:@]+$/;
|
|
15403
|
+
for (const arg of conn.server.transport.args) {
|
|
15404
|
+
if (!SAFE_ARG_PATTERN.test(arg)) {
|
|
15405
|
+
throw new Error(`Unsafe argument rejected: contains disallowed characters`);
|
|
15406
|
+
}
|
|
15407
|
+
}
|
|
15408
|
+
}
|
|
15409
|
+
const ENV_BLOCKLIST = /* @__PURE__ */ new Set([
|
|
15410
|
+
"PATH",
|
|
15411
|
+
"HOME",
|
|
15412
|
+
"USER",
|
|
15413
|
+
"SHELL",
|
|
15414
|
+
"NODE_OPTIONS",
|
|
15415
|
+
"NODE_PATH",
|
|
15416
|
+
"LD_PRELOAD",
|
|
15417
|
+
"LD_LIBRARY_PATH",
|
|
15418
|
+
"DYLD_INSERT_LIBRARIES",
|
|
15419
|
+
"PYTHONPATH",
|
|
15420
|
+
"RUBYLIB",
|
|
15421
|
+
"PERL5LIB",
|
|
15422
|
+
"HTTP_PROXY",
|
|
15423
|
+
"HTTPS_PROXY",
|
|
15424
|
+
"NO_PROXY",
|
|
15425
|
+
"http_proxy",
|
|
15426
|
+
"https_proxy",
|
|
15427
|
+
"no_proxy"
|
|
15428
|
+
]);
|
|
15429
|
+
let transportEnv;
|
|
15430
|
+
if (conn.server.transport.env) {
|
|
15431
|
+
const safeEnv = { ...process.env };
|
|
15432
|
+
for (const [key, value] of Object.entries(conn.server.transport.env)) {
|
|
15433
|
+
if (!ENV_BLOCKLIST.has(key)) {
|
|
15434
|
+
safeEnv[key] = value;
|
|
15435
|
+
}
|
|
15436
|
+
}
|
|
15437
|
+
transportEnv = safeEnv;
|
|
15438
|
+
}
|
|
15439
|
+
transport = new StdioClientTransport({
|
|
15440
|
+
command: conn.server.transport.command,
|
|
15441
|
+
args: conn.server.transport.args,
|
|
15442
|
+
env: transportEnv
|
|
15443
|
+
});
|
|
15444
|
+
} else {
|
|
15445
|
+
if (!conn.server.transport.url) {
|
|
15446
|
+
throw new Error("sse transport requires a url");
|
|
15447
|
+
}
|
|
15448
|
+
const ssrfUrl = new URL(conn.server.transport.url);
|
|
15449
|
+
if (ssrfUrl.protocol !== "http:" && ssrfUrl.protocol !== "https:") {
|
|
15450
|
+
throw new Error("SSE transport URL must use http or https scheme");
|
|
15451
|
+
}
|
|
15452
|
+
transport = new SSEClientTransport(ssrfUrl);
|
|
15453
|
+
}
|
|
15454
|
+
const client = new Client(
|
|
15455
|
+
{ name: `sanctuary-proxy/${conn.server.name}`, version: "1.0.0" },
|
|
15456
|
+
{ capabilities: {} }
|
|
15457
|
+
);
|
|
15458
|
+
await client.connect(transport);
|
|
15459
|
+
conn.client = client;
|
|
15460
|
+
conn.transport = transport;
|
|
15461
|
+
conn.state = "connected";
|
|
15462
|
+
conn.error = void 0;
|
|
15463
|
+
conn.retryCount = 0;
|
|
15464
|
+
await this.discoverTools(conn);
|
|
15465
|
+
this.notifyStateChange(conn);
|
|
15466
|
+
} catch (err) {
|
|
15467
|
+
const message = err instanceof Error ? err.message : "Unknown connection error";
|
|
15468
|
+
conn.state = "error";
|
|
15469
|
+
conn.error = message;
|
|
15470
|
+
conn.client = null;
|
|
15471
|
+
conn.transport = null;
|
|
15472
|
+
this.notifyStateChange(conn);
|
|
15473
|
+
this.scheduleRetry(conn);
|
|
15474
|
+
}
|
|
15475
|
+
}
|
|
15476
|
+
/**
|
|
15477
|
+
* Discover tools from a connected upstream server.
|
|
15478
|
+
*/
|
|
15479
|
+
async discoverTools(conn) {
|
|
15480
|
+
if (!conn.client || conn.state !== "connected") return;
|
|
15481
|
+
try {
|
|
15482
|
+
const result = await conn.client.listTools();
|
|
15483
|
+
conn.tools = (result.tools ?? []).map((t) => ({
|
|
15484
|
+
name: t.name,
|
|
15485
|
+
description: t.description ?? "",
|
|
15486
|
+
inputSchema: t.inputSchema ?? { type: "object", properties: {} }
|
|
15487
|
+
}));
|
|
15488
|
+
} catch {
|
|
15489
|
+
conn.tools = [];
|
|
15490
|
+
}
|
|
15491
|
+
}
|
|
15492
|
+
/**
|
|
15493
|
+
* Schedule a reconnection attempt with exponential backoff.
|
|
15494
|
+
*/
|
|
15495
|
+
scheduleRetry(conn) {
|
|
15496
|
+
if (this.shutdownRequested) return;
|
|
15497
|
+
if (conn.retryCount >= MAX_RETRIES) {
|
|
15498
|
+
conn.error = `Max retries (${MAX_RETRIES}) exceeded. Last error: ${conn.error}`;
|
|
15499
|
+
this.notifyStateChange(conn);
|
|
15500
|
+
return;
|
|
15501
|
+
}
|
|
15502
|
+
const delay = Math.min(
|
|
15503
|
+
BASE_BACKOFF_MS * Math.pow(2, conn.retryCount),
|
|
15504
|
+
MAX_BACKOFF_MS
|
|
15505
|
+
);
|
|
15506
|
+
conn.retryCount++;
|
|
15507
|
+
conn.retryTimer = setTimeout(() => {
|
|
15508
|
+
if (this.shutdownRequested) return;
|
|
15509
|
+
conn.retryTimer = void 0;
|
|
15510
|
+
this.doConnect(conn).catch(() => {
|
|
15511
|
+
});
|
|
15512
|
+
}, delay);
|
|
15513
|
+
}
|
|
15514
|
+
/**
|
|
15515
|
+
* Disconnect a specific upstream server.
|
|
15516
|
+
*/
|
|
15517
|
+
async disconnectServer(name) {
|
|
15518
|
+
const conn = this.connections.get(name);
|
|
15519
|
+
if (!conn) return;
|
|
15520
|
+
if (conn.retryTimer) {
|
|
15521
|
+
clearTimeout(conn.retryTimer);
|
|
15522
|
+
conn.retryTimer = void 0;
|
|
15523
|
+
}
|
|
15524
|
+
if (conn.client) {
|
|
15525
|
+
try {
|
|
15526
|
+
await conn.client.close();
|
|
15527
|
+
} catch {
|
|
15528
|
+
}
|
|
15529
|
+
}
|
|
15530
|
+
if (conn.transport) {
|
|
15531
|
+
try {
|
|
15532
|
+
await conn.transport.close();
|
|
15533
|
+
} catch {
|
|
15534
|
+
}
|
|
15535
|
+
}
|
|
15536
|
+
this.connections.delete(name);
|
|
15537
|
+
}
|
|
15538
|
+
/**
|
|
15539
|
+
* Notify listener of state change.
|
|
15540
|
+
*/
|
|
15541
|
+
notifyStateChange(conn) {
|
|
15542
|
+
if (this.onStateChange) {
|
|
15543
|
+
try {
|
|
15544
|
+
this.onStateChange(conn.server.name, conn.state, conn.tools.length, conn.error);
|
|
15545
|
+
} catch {
|
|
15546
|
+
}
|
|
15547
|
+
}
|
|
15548
|
+
}
|
|
15549
|
+
};
|
|
15550
|
+
|
|
15551
|
+
// src/proxy/proxy-router.ts
|
|
15552
|
+
init_router();
|
|
15553
|
+
var UPSTREAM_CALL_TIMEOUT_MS = 3e4;
|
|
15554
|
+
var ProxyRouter = class {
|
|
15555
|
+
clientManager;
|
|
15556
|
+
injectionDetector;
|
|
15557
|
+
auditLog;
|
|
15558
|
+
options;
|
|
15559
|
+
constructor(clientManager, injectionDetector, auditLog, options) {
|
|
15560
|
+
this.clientManager = clientManager;
|
|
15561
|
+
this.injectionDetector = injectionDetector;
|
|
15562
|
+
this.auditLog = auditLog;
|
|
15563
|
+
this.options = options ?? {};
|
|
15564
|
+
}
|
|
15565
|
+
/**
|
|
15566
|
+
* Convert all discovered upstream tools to Sanctuary ToolDefinitions.
|
|
15567
|
+
* Each tool is registered as `proxy/{server_name}/{tool_name}`.
|
|
15568
|
+
*/
|
|
15569
|
+
getProxiedTools() {
|
|
15570
|
+
const tools = [];
|
|
15571
|
+
const allUpstreamTools = this.clientManager.getAllTools();
|
|
15572
|
+
for (const [serverName, serverTools] of allUpstreamTools) {
|
|
15573
|
+
for (const upstreamTool of serverTools) {
|
|
15574
|
+
const proxyName = `proxy/${serverName}/${upstreamTool.name}`;
|
|
15575
|
+
tools.push({
|
|
15576
|
+
name: proxyName,
|
|
15577
|
+
description: `[via ${serverName}] ${upstreamTool.description}`,
|
|
15578
|
+
inputSchema: upstreamTool.inputSchema,
|
|
15579
|
+
handler: this.createHandler(serverName, upstreamTool.name)
|
|
15580
|
+
});
|
|
15581
|
+
}
|
|
15582
|
+
}
|
|
15583
|
+
return tools;
|
|
15584
|
+
}
|
|
15585
|
+
/**
|
|
15586
|
+
* Determine the tier for a proxied tool call.
|
|
15587
|
+
* Checks tool_overrides first, then falls back to default_tier.
|
|
15588
|
+
*/
|
|
15589
|
+
getTierForTool(serverName, toolName) {
|
|
15590
|
+
const serverConfig = this.clientManager.getServerConfig(serverName);
|
|
15591
|
+
if (!serverConfig) return 2;
|
|
15592
|
+
if (serverConfig.tool_overrides?.[toolName]) {
|
|
15593
|
+
return serverConfig.tool_overrides[toolName].tier;
|
|
15594
|
+
}
|
|
15595
|
+
return serverConfig.default_tier;
|
|
15596
|
+
}
|
|
15597
|
+
/**
|
|
15598
|
+
* Parse a proxy tool name into server name and tool name.
|
|
15599
|
+
* Returns null if the name doesn't match the proxy namespace.
|
|
15600
|
+
*/
|
|
15601
|
+
static parseProxyToolName(fullName) {
|
|
15602
|
+
if (!fullName.startsWith("proxy/")) return null;
|
|
15603
|
+
const rest = fullName.slice("proxy/".length);
|
|
15604
|
+
const slashIdx = rest.indexOf("/");
|
|
15605
|
+
if (slashIdx === -1) return null;
|
|
15606
|
+
return {
|
|
15607
|
+
serverName: rest.slice(0, slashIdx),
|
|
15608
|
+
toolName: rest.slice(slashIdx + 1)
|
|
15609
|
+
};
|
|
15610
|
+
}
|
|
15611
|
+
// ── Private ───────────────────────────────────────────────────────────
|
|
15612
|
+
/**
|
|
15613
|
+
* Create a handler for a specific proxied tool.
|
|
15614
|
+
* The handler runs the full enforcement chain before forwarding.
|
|
15615
|
+
*/
|
|
15616
|
+
createHandler(serverName, toolName) {
|
|
15617
|
+
return async (args) => {
|
|
15618
|
+
const proxyName = `proxy/${serverName}/${toolName}`;
|
|
15619
|
+
const start = Date.now();
|
|
15620
|
+
const tier = this.getTierForTool(serverName, toolName);
|
|
15621
|
+
try {
|
|
15622
|
+
const injectionResult = this.injectionDetector.scan(proxyName, args);
|
|
15623
|
+
if (injectionResult.flagged && injectionResult.recommendation === "block") {
|
|
15624
|
+
this.auditLog.append("l2", `proxy_injection_blocked:${proxyName}`, "system", {
|
|
15625
|
+
server: serverName,
|
|
15626
|
+
tool: toolName,
|
|
15627
|
+
tier,
|
|
15628
|
+
confidence: injectionResult.confidence,
|
|
15629
|
+
latency_ms: Date.now() - start
|
|
15630
|
+
}, "failure");
|
|
15631
|
+
return toolResult({
|
|
15632
|
+
error: "Operation not permitted",
|
|
15633
|
+
proxy: true
|
|
15634
|
+
});
|
|
15635
|
+
}
|
|
15636
|
+
if (injectionResult.flagged && injectionResult.recommendation === "escalate") {
|
|
15637
|
+
this.auditLog.append("l2", `proxy_injection_escalated:${proxyName}`, "system", {
|
|
15638
|
+
server: serverName,
|
|
15639
|
+
tool: toolName,
|
|
15640
|
+
tier,
|
|
15641
|
+
confidence: injectionResult.confidence
|
|
15642
|
+
});
|
|
15643
|
+
}
|
|
15644
|
+
let filteredArgs = args;
|
|
15645
|
+
if (this.options.contextGateFilter) {
|
|
15646
|
+
try {
|
|
15647
|
+
filteredArgs = await this.options.contextGateFilter(proxyName, args);
|
|
15648
|
+
} catch {
|
|
15649
|
+
}
|
|
15650
|
+
}
|
|
15651
|
+
if (this.options.governor) {
|
|
15652
|
+
const govResult = this.options.governor.check(serverName, toolName, filteredArgs);
|
|
15653
|
+
if (!govResult.allowed) {
|
|
15654
|
+
this.auditLog.append("l2", `proxy_governor_blocked:${proxyName}`, "system", {
|
|
15655
|
+
server: serverName,
|
|
15656
|
+
tool: toolName,
|
|
15657
|
+
tier,
|
|
15658
|
+
reason: govResult.reason,
|
|
15659
|
+
latency_ms: Date.now() - start
|
|
15660
|
+
}, "failure");
|
|
15661
|
+
return toolResult({
|
|
15662
|
+
error: "Operation not permitted",
|
|
15663
|
+
proxy: true,
|
|
15664
|
+
governor_reason: govResult.reason
|
|
15665
|
+
});
|
|
15666
|
+
}
|
|
15667
|
+
if (govResult.reason === "duplicate_cached" && govResult.cached_result !== void 0) {
|
|
15668
|
+
this.auditLog.append("l2", `proxy_governor_cached:${proxyName}`, "system", {
|
|
15669
|
+
server: serverName,
|
|
15670
|
+
tool: toolName,
|
|
15671
|
+
tier,
|
|
15672
|
+
cached: true,
|
|
15673
|
+
latency_ms: Date.now() - start
|
|
15674
|
+
});
|
|
15675
|
+
return toolResult(govResult.cached_result ?? {});
|
|
15676
|
+
}
|
|
15677
|
+
}
|
|
15678
|
+
const result = await this.callWithTimeout(
|
|
15679
|
+
serverName,
|
|
15680
|
+
toolName,
|
|
15681
|
+
filteredArgs,
|
|
15682
|
+
UPSTREAM_CALL_TIMEOUT_MS
|
|
15683
|
+
);
|
|
15684
|
+
const latencyMs = Date.now() - start;
|
|
15685
|
+
if (this.options.governor) {
|
|
15686
|
+
this.options.governor.recordResult(serverName, toolName, filteredArgs, result);
|
|
15687
|
+
}
|
|
15688
|
+
this.auditLog.append("l2", `proxy_call:${proxyName}`, "system", {
|
|
15689
|
+
server: serverName,
|
|
15690
|
+
tool: toolName,
|
|
15691
|
+
tier,
|
|
15692
|
+
decision: "allowed",
|
|
15693
|
+
latency_ms: latencyMs
|
|
15694
|
+
});
|
|
15695
|
+
return this.normalizeResponse(result);
|
|
15696
|
+
} catch (err) {
|
|
15697
|
+
const latencyMs = Date.now() - start;
|
|
15698
|
+
const rawErrorMessage = err instanceof Error ? err.message : "Unknown upstream error";
|
|
15699
|
+
const sanitizeError = (msg) => {
|
|
15700
|
+
let safe = msg.substring(0, 200);
|
|
15701
|
+
safe = safe.replace(/\/[^\s]+/g, "[path-redacted]");
|
|
15702
|
+
safe = safe.replace(/(?:mongodb|postgres|mysql|redis):\/\/[^\s]+/g, "[connection-redacted]");
|
|
15703
|
+
return safe;
|
|
15704
|
+
};
|
|
15705
|
+
const errorMessage = sanitizeError(rawErrorMessage);
|
|
15706
|
+
this.auditLog.append("l2", `proxy_call:${proxyName}`, "system", {
|
|
15707
|
+
server: serverName,
|
|
15708
|
+
tool: toolName,
|
|
15709
|
+
tier,
|
|
15710
|
+
decision: "error",
|
|
15711
|
+
error: errorMessage,
|
|
15712
|
+
latency_ms: latencyMs
|
|
15713
|
+
}, "failure");
|
|
15714
|
+
return {
|
|
15715
|
+
content: [{
|
|
15716
|
+
type: "text",
|
|
15717
|
+
text: JSON.stringify({
|
|
15718
|
+
error: errorMessage,
|
|
15719
|
+
proxy: true,
|
|
15720
|
+
server: serverName,
|
|
15721
|
+
tool: toolName
|
|
15722
|
+
})
|
|
15723
|
+
}]
|
|
15724
|
+
};
|
|
15725
|
+
}
|
|
15726
|
+
};
|
|
15727
|
+
}
|
|
15728
|
+
/**
|
|
15729
|
+
* Call an upstream tool with a timeout.
|
|
15730
|
+
*/
|
|
15731
|
+
async callWithTimeout(serverName, toolName, args, timeoutMs) {
|
|
15732
|
+
return new Promise((resolve, reject) => {
|
|
15733
|
+
const timer = setTimeout(() => {
|
|
15734
|
+
reject(new Error(`Upstream tool call timed out after ${timeoutMs}ms`));
|
|
15735
|
+
}, timeoutMs);
|
|
15736
|
+
this.clientManager.callTool(serverName, toolName, args).then((result) => {
|
|
15737
|
+
clearTimeout(timer);
|
|
15738
|
+
resolve(result);
|
|
15739
|
+
}).catch((err) => {
|
|
15740
|
+
clearTimeout(timer);
|
|
15741
|
+
reject(err);
|
|
15742
|
+
});
|
|
15743
|
+
});
|
|
15744
|
+
}
|
|
15745
|
+
/**
|
|
15746
|
+
* Normalize an upstream response to the standard Sanctuary response format.
|
|
15747
|
+
*/
|
|
15748
|
+
normalizeResponse(result) {
|
|
15749
|
+
const MAX_RESPONSE_SIZE = 1e6;
|
|
15750
|
+
const MAX_TEXT_BLOCK_SIZE = 1e5;
|
|
15751
|
+
const responseStr = JSON.stringify(result);
|
|
15752
|
+
if (responseStr.length > MAX_RESPONSE_SIZE) {
|
|
15753
|
+
return toolResult({
|
|
15754
|
+
error: "upstream_response_too_large",
|
|
15755
|
+
max_bytes: MAX_RESPONSE_SIZE
|
|
15756
|
+
});
|
|
15757
|
+
}
|
|
15758
|
+
if (!result.content || !Array.isArray(result.content)) {
|
|
15759
|
+
return toolResult({ upstream_response: result });
|
|
15760
|
+
}
|
|
15761
|
+
const textContent = result.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => {
|
|
15762
|
+
const text = c.text;
|
|
15763
|
+
if (text.length > MAX_TEXT_BLOCK_SIZE) {
|
|
15764
|
+
return {
|
|
15765
|
+
type: "text",
|
|
15766
|
+
text: text.substring(0, MAX_TEXT_BLOCK_SIZE) + "\n[response truncated]"
|
|
15767
|
+
};
|
|
15768
|
+
}
|
|
15769
|
+
return { type: "text", text };
|
|
15770
|
+
});
|
|
15771
|
+
if (textContent.length > 0) {
|
|
15772
|
+
return { content: textContent };
|
|
15773
|
+
}
|
|
15774
|
+
return toolResult({ upstream_response: result.content });
|
|
15775
|
+
}
|
|
15776
|
+
};
|
|
15777
|
+
function strToBytes(s) {
|
|
15778
|
+
return new TextEncoder().encode(s);
|
|
15779
|
+
}
|
|
15780
|
+
function bytesToHex(bytes) {
|
|
15781
|
+
let hex = "";
|
|
15782
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
15783
|
+
hex += bytes[i].toString(16).padStart(2, "0");
|
|
15784
|
+
}
|
|
15785
|
+
return hex;
|
|
15786
|
+
}
|
|
15787
|
+
function sha256Hex(input) {
|
|
15788
|
+
return bytesToHex(sha256(strToBytes(input)));
|
|
15789
|
+
}
|
|
15790
|
+
var DEFAULT_CONFIG = {
|
|
15791
|
+
volume_limit: 200,
|
|
15792
|
+
volume_window_ms: 6e5,
|
|
15793
|
+
// 10 minutes
|
|
15794
|
+
rate_limit: 20,
|
|
15795
|
+
rate_window_ms: 6e4,
|
|
15796
|
+
// 1 minute
|
|
15797
|
+
duplicate_ttl_ms: 6e4,
|
|
15798
|
+
// 1 minute
|
|
15799
|
+
lifetime_limit: 1e3
|
|
15800
|
+
};
|
|
15801
|
+
var CallGovernor = class {
|
|
15802
|
+
config;
|
|
15803
|
+
/** Sliding window of all call timestamps for volume tracking */
|
|
15804
|
+
volumeWindow = [];
|
|
15805
|
+
/** Per-tool sliding window of call timestamps for rate tracking */
|
|
15806
|
+
rateWindows = /* @__PURE__ */ new Map();
|
|
15807
|
+
/** Duplicate cache: SHA-256(server+tool+args) -> cached result + expiry */
|
|
15808
|
+
duplicateCache = /* @__PURE__ */ new Map();
|
|
15809
|
+
/** Total calls this session */
|
|
15810
|
+
lifetimeCount = 0;
|
|
15811
|
+
/** Hard stop flag — set when lifetime limit is reached */
|
|
15812
|
+
hardStopped = false;
|
|
15813
|
+
constructor(config) {
|
|
15814
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
15815
|
+
}
|
|
15816
|
+
/**
|
|
15817
|
+
* Check if a call is allowed and apply governance.
|
|
15818
|
+
*
|
|
15819
|
+
* Evaluation order:
|
|
15820
|
+
* 1. Lifetime limit (hard stop — not recoverable without reset)
|
|
15821
|
+
* 2. Volume limit (sliding window)
|
|
15822
|
+
* 3. Rate limit per tool (escalates to Tier 2)
|
|
15823
|
+
* 4. Duplicate detection (returns cached result)
|
|
15824
|
+
*/
|
|
15825
|
+
check(serverName, toolName, args) {
|
|
15826
|
+
const now = Date.now();
|
|
15827
|
+
const effectiveConfig = this.getEffectiveConfig(serverName);
|
|
15828
|
+
if (this.hardStopped) {
|
|
15829
|
+
return {
|
|
15830
|
+
allowed: false,
|
|
15831
|
+
reason: "lifetime_exceeded"
|
|
15832
|
+
};
|
|
15833
|
+
}
|
|
15834
|
+
if (this.lifetimeCount >= effectiveConfig.lifetime_limit) {
|
|
15835
|
+
this.hardStopped = true;
|
|
15836
|
+
return {
|
|
15837
|
+
allowed: false,
|
|
15838
|
+
reason: "lifetime_exceeded"
|
|
15839
|
+
};
|
|
15840
|
+
}
|
|
15841
|
+
this.pruneVolumeWindow(now, effectiveConfig.volume_window_ms);
|
|
15842
|
+
if (this.volumeWindow.length >= effectiveConfig.volume_limit) {
|
|
15843
|
+
return {
|
|
15844
|
+
allowed: false,
|
|
15845
|
+
reason: "volume_exceeded"
|
|
15846
|
+
};
|
|
15847
|
+
}
|
|
15848
|
+
const toolKey = `${serverName}::${toolName}`;
|
|
15849
|
+
this.pruneRateWindow(toolKey, now, effectiveConfig.rate_window_ms);
|
|
15850
|
+
const rateWindow = this.rateWindows.get(toolKey);
|
|
15851
|
+
const currentRate = rateWindow ? rateWindow.length : 0;
|
|
15852
|
+
if (currentRate >= effectiveConfig.rate_limit) {
|
|
15853
|
+
return {
|
|
15854
|
+
allowed: false,
|
|
15855
|
+
reason: "rate_exceeded",
|
|
15856
|
+
escalate: true
|
|
15857
|
+
};
|
|
15858
|
+
}
|
|
15859
|
+
const callHash = this.computeCallHash(serverName, toolName, args);
|
|
15860
|
+
this.pruneDuplicateCache(now);
|
|
15861
|
+
const cached = this.duplicateCache.get(callHash);
|
|
15862
|
+
if (cached && cached.expires_at > now) {
|
|
15863
|
+
return {
|
|
15864
|
+
allowed: true,
|
|
15865
|
+
reason: "duplicate_cached",
|
|
15866
|
+
cached_result: cached.result
|
|
15867
|
+
};
|
|
15868
|
+
}
|
|
15869
|
+
this.volumeWindow.push(now);
|
|
15870
|
+
if (!this.rateWindows.has(toolKey)) {
|
|
15871
|
+
this.rateWindows.set(toolKey, []);
|
|
15872
|
+
}
|
|
15873
|
+
this.rateWindows.get(toolKey).push(now);
|
|
15874
|
+
this.lifetimeCount++;
|
|
15875
|
+
return { allowed: true };
|
|
15876
|
+
}
|
|
15877
|
+
/**
|
|
15878
|
+
* Record a successful call result for duplicate caching.
|
|
15879
|
+
*/
|
|
15880
|
+
recordResult(serverName, toolName, args, result) {
|
|
15881
|
+
const callHash = this.computeCallHash(serverName, toolName, args);
|
|
15882
|
+
const effectiveConfig = this.getEffectiveConfig(serverName);
|
|
15883
|
+
this.duplicateCache.set(callHash, {
|
|
15884
|
+
result,
|
|
15885
|
+
expires_at: Date.now() + effectiveConfig.duplicate_ttl_ms
|
|
15886
|
+
});
|
|
15887
|
+
}
|
|
15888
|
+
/**
|
|
15889
|
+
* Get current governor status for dashboard display.
|
|
15890
|
+
*/
|
|
15891
|
+
getStatus() {
|
|
15892
|
+
const now = Date.now();
|
|
15893
|
+
this.pruneVolumeWindow(now, this.config.volume_window_ms);
|
|
15894
|
+
this.pruneDuplicateCache(now);
|
|
15895
|
+
const rateByTool = {};
|
|
15896
|
+
for (const [toolKey, timestamps] of this.rateWindows.entries()) {
|
|
15897
|
+
const cutoff = now - this.config.rate_window_ms;
|
|
15898
|
+
const activeCount = timestamps.filter((t) => t >= cutoff).length;
|
|
15899
|
+
if (activeCount > 0) {
|
|
15900
|
+
rateByTool[toolKey] = activeCount;
|
|
15901
|
+
}
|
|
15902
|
+
}
|
|
15903
|
+
return {
|
|
15904
|
+
volume_current: this.volumeWindow.length,
|
|
15905
|
+
volume_limit: this.config.volume_limit,
|
|
15906
|
+
lifetime_current: this.lifetimeCount,
|
|
15907
|
+
lifetime_limit: this.config.lifetime_limit,
|
|
15908
|
+
rate_by_tool: rateByTool,
|
|
15909
|
+
duplicate_cache_size: this.duplicateCache.size,
|
|
15910
|
+
hard_stopped: this.hardStopped
|
|
15911
|
+
};
|
|
15912
|
+
}
|
|
15913
|
+
/**
|
|
15914
|
+
* Reset all counters (Tier 1 — requires approval).
|
|
15915
|
+
* Clears volume window, rate windows, duplicate cache,
|
|
15916
|
+
* lifetime counter, and hard stop flag.
|
|
15917
|
+
*/
|
|
15918
|
+
reset() {
|
|
15919
|
+
this.volumeWindow = [];
|
|
15920
|
+
this.rateWindows.clear();
|
|
15921
|
+
this.duplicateCache.clear();
|
|
15922
|
+
this.lifetimeCount = 0;
|
|
15923
|
+
this.hardStopped = false;
|
|
15924
|
+
}
|
|
15925
|
+
/**
|
|
15926
|
+
* Get the effective config for a given server, merging per-server overrides.
|
|
15927
|
+
*/
|
|
15928
|
+
getEffectiveConfig(serverName) {
|
|
15929
|
+
const override = this.config.per_server_overrides?.[serverName];
|
|
15930
|
+
if (!override) return this.config;
|
|
15931
|
+
return { ...this.config, ...override };
|
|
15932
|
+
}
|
|
15933
|
+
/**
|
|
15934
|
+
* Compute a SHA-256 hash of server + tool + canonical args.
|
|
15935
|
+
* Used for duplicate detection.
|
|
15936
|
+
*/
|
|
15937
|
+
computeCallHash(serverName, toolName, args) {
|
|
15938
|
+
const stableArgs = this.stableStringify(args);
|
|
15939
|
+
const input = `${serverName}\0${toolName}\0${stableArgs}`;
|
|
15940
|
+
return sha256Hex(input);
|
|
15941
|
+
}
|
|
15942
|
+
/**
|
|
15943
|
+
* Deterministic JSON serialization with sorted keys.
|
|
15944
|
+
*/
|
|
15945
|
+
stableStringify(obj) {
|
|
15946
|
+
if (obj === null || obj === void 0) return "null";
|
|
15947
|
+
if (typeof obj !== "object") return JSON.stringify(obj);
|
|
15948
|
+
if (Array.isArray(obj)) {
|
|
15949
|
+
return "[" + obj.map((item) => this.stableStringify(item)).join(",") + "]";
|
|
15950
|
+
}
|
|
15951
|
+
const sortedKeys = Object.keys(obj).sort();
|
|
15952
|
+
const pairs = sortedKeys.map(
|
|
15953
|
+
(key) => JSON.stringify(key) + ":" + this.stableStringify(obj[key])
|
|
15954
|
+
);
|
|
15955
|
+
return "{" + pairs.join(",") + "}";
|
|
15956
|
+
}
|
|
15957
|
+
/**
|
|
15958
|
+
* Prune volume window entries older than the window size.
|
|
15959
|
+
* Uses shift() from the front — timestamps are appended in order.
|
|
15960
|
+
*/
|
|
15961
|
+
pruneVolumeWindow(now, windowMs) {
|
|
15962
|
+
const cutoff = now - windowMs;
|
|
15963
|
+
while (this.volumeWindow.length > 0 && this.volumeWindow[0] < cutoff) {
|
|
15964
|
+
this.volumeWindow.shift();
|
|
15965
|
+
}
|
|
15966
|
+
}
|
|
15967
|
+
/**
|
|
15968
|
+
* Prune a per-tool rate window.
|
|
15969
|
+
*/
|
|
15970
|
+
pruneRateWindow(toolKey, now, windowMs) {
|
|
15971
|
+
const window = this.rateWindows.get(toolKey);
|
|
15972
|
+
if (!window) return;
|
|
15973
|
+
const cutoff = now - windowMs;
|
|
15974
|
+
while (window.length > 0 && window[0] < cutoff) {
|
|
15975
|
+
window.shift();
|
|
15976
|
+
}
|
|
15977
|
+
if (window.length === 0) {
|
|
15978
|
+
this.rateWindows.delete(toolKey);
|
|
15979
|
+
}
|
|
15980
|
+
}
|
|
15981
|
+
/**
|
|
15982
|
+
* Prune expired entries from the duplicate cache.
|
|
15983
|
+
* Amortized O(1) — only prunes when cache exceeds a size threshold.
|
|
15984
|
+
*/
|
|
15985
|
+
pruneDuplicateCache(now) {
|
|
15986
|
+
if (this.duplicateCache.size < 100) return;
|
|
15987
|
+
for (const [key, entry] of this.duplicateCache) {
|
|
15988
|
+
if (entry.expires_at <= now) {
|
|
15989
|
+
this.duplicateCache.delete(key);
|
|
15990
|
+
}
|
|
15991
|
+
}
|
|
15992
|
+
}
|
|
15993
|
+
};
|
|
15994
|
+
|
|
15995
|
+
// src/l2-operational/governor-tools.ts
|
|
15996
|
+
init_router();
|
|
15997
|
+
function createGovernorTools(governor, auditLog) {
|
|
15998
|
+
const tools = [
|
|
15999
|
+
// ── Governor Status ─────────────────────────────────────────────
|
|
16000
|
+
{
|
|
16001
|
+
name: "sanctuary/governor_status",
|
|
16002
|
+
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.",
|
|
16003
|
+
inputSchema: {
|
|
16004
|
+
type: "object",
|
|
16005
|
+
properties: {}
|
|
16006
|
+
},
|
|
16007
|
+
handler: async () => {
|
|
16008
|
+
const status = governor.getStatus();
|
|
16009
|
+
auditLog.append("l2", "governor_status", "system", {
|
|
16010
|
+
volume_current: status.volume_current,
|
|
16011
|
+
volume_limit: status.volume_limit,
|
|
16012
|
+
lifetime_current: status.lifetime_current,
|
|
16013
|
+
lifetime_limit: status.lifetime_limit,
|
|
16014
|
+
duplicate_cache_size: status.duplicate_cache_size,
|
|
16015
|
+
hard_stopped: status.hard_stopped
|
|
16016
|
+
});
|
|
16017
|
+
const volumePercent = status.volume_limit > 0 ? Math.round(status.volume_current / status.volume_limit * 100) : 0;
|
|
16018
|
+
const lifetimePercent = status.lifetime_limit > 0 ? Math.round(status.lifetime_current / status.lifetime_limit * 100) : 0;
|
|
16019
|
+
const toolRateEntries = Object.entries(status.rate_by_tool);
|
|
16020
|
+
const highRateTools = toolRateEntries.filter(([, count]) => count > 10).map(([tool, count]) => `${tool} (${count} calls/min)`);
|
|
16021
|
+
return toolResult({
|
|
16022
|
+
governor_status: status,
|
|
16023
|
+
summary: {
|
|
16024
|
+
volume_usage: `${status.volume_current}/${status.volume_limit} (${volumePercent}%)`,
|
|
16025
|
+
lifetime_usage: `${status.lifetime_current}/${status.lifetime_limit} (${lifetimePercent}%)`,
|
|
16026
|
+
active_tools: toolRateEntries.length,
|
|
16027
|
+
cached_duplicates: status.duplicate_cache_size
|
|
16028
|
+
},
|
|
16029
|
+
warnings: [
|
|
16030
|
+
...status.hard_stopped ? ["HARD STOP: Lifetime limit reached. Use sanctuary/governor_reset to continue."] : [],
|
|
16031
|
+
...volumePercent > 80 ? [`Volume usage at ${volumePercent}% \u2014 approaching limit.`] : [],
|
|
16032
|
+
...lifetimePercent > 80 ? [`Lifetime usage at ${lifetimePercent}% \u2014 approaching hard stop.`] : [],
|
|
16033
|
+
...highRateTools.length > 0 ? [`High-rate tools detected: ${highRateTools.join(", ")}`] : []
|
|
16034
|
+
],
|
|
16035
|
+
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."
|
|
16036
|
+
});
|
|
16037
|
+
}
|
|
16038
|
+
},
|
|
16039
|
+
// ── Governor Reset ──────────────────────────────────────────────
|
|
16040
|
+
{
|
|
16041
|
+
name: "sanctuary/governor_reset",
|
|
16042
|
+
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.",
|
|
16043
|
+
inputSchema: {
|
|
16044
|
+
type: "object",
|
|
16045
|
+
properties: {
|
|
16046
|
+
confirm: {
|
|
16047
|
+
type: "boolean",
|
|
16048
|
+
description: "Must be true to confirm the reset. This clears all governor state including the lifetime counter."
|
|
16049
|
+
}
|
|
16050
|
+
},
|
|
16051
|
+
required: ["confirm"]
|
|
16052
|
+
},
|
|
16053
|
+
handler: async (args) => {
|
|
16054
|
+
const confirm = args.confirm;
|
|
16055
|
+
if (!confirm) {
|
|
16056
|
+
return toolResult({
|
|
16057
|
+
error: "confirmation_required",
|
|
16058
|
+
message: "Set confirm: true to reset all governor counters. This will clear volume limits, rate tracking, duplicate cache, and the lifetime counter."
|
|
16059
|
+
});
|
|
16060
|
+
}
|
|
16061
|
+
const preResetStatus = governor.getStatus();
|
|
16062
|
+
governor.reset();
|
|
16063
|
+
const postResetStatus = governor.getStatus();
|
|
16064
|
+
auditLog.append("l2", "governor_reset", "system", {
|
|
16065
|
+
pre_reset: {
|
|
16066
|
+
volume_current: preResetStatus.volume_current,
|
|
16067
|
+
lifetime_current: preResetStatus.lifetime_current,
|
|
16068
|
+
duplicate_cache_size: preResetStatus.duplicate_cache_size,
|
|
16069
|
+
hard_stopped: preResetStatus.hard_stopped
|
|
16070
|
+
},
|
|
16071
|
+
post_reset: {
|
|
16072
|
+
volume_current: postResetStatus.volume_current,
|
|
16073
|
+
lifetime_current: postResetStatus.lifetime_current,
|
|
16074
|
+
duplicate_cache_size: postResetStatus.duplicate_cache_size,
|
|
16075
|
+
hard_stopped: postResetStatus.hard_stopped
|
|
16076
|
+
}
|
|
16077
|
+
});
|
|
16078
|
+
return toolResult({
|
|
16079
|
+
reset: true,
|
|
16080
|
+
previous_state: {
|
|
16081
|
+
lifetime_calls: preResetStatus.lifetime_current,
|
|
16082
|
+
was_hard_stopped: preResetStatus.hard_stopped,
|
|
16083
|
+
volume_at_reset: preResetStatus.volume_current,
|
|
16084
|
+
cached_duplicates_cleared: preResetStatus.duplicate_cache_size
|
|
16085
|
+
},
|
|
16086
|
+
current_state: postResetStatus,
|
|
16087
|
+
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.")
|
|
16088
|
+
});
|
|
16089
|
+
}
|
|
16090
|
+
}
|
|
16091
|
+
];
|
|
16092
|
+
return { tools };
|
|
16093
|
+
}
|
|
16094
|
+
|
|
16095
|
+
// src/index.ts
|
|
16096
|
+
init_key_derivation();
|
|
16097
|
+
init_random();
|
|
16098
|
+
init_encoding();
|
|
16099
|
+
init_config();
|
|
16100
|
+
init_audit_log();
|
|
16101
|
+
init_sovereignty_profile();
|
|
16102
|
+
init_system_prompt_generator();
|
|
16103
|
+
init_filesystem();
|
|
16104
|
+
init_baseline();
|
|
16105
|
+
init_loader();
|
|
16106
|
+
init_dashboard();
|
|
16107
|
+
init_generator();
|
|
16108
|
+
async function createSanctuaryServer(options) {
|
|
16109
|
+
const config = await loadConfig(options?.configPath);
|
|
13649
16110
|
await mkdir(config.storage_path, { recursive: true, mode: 448 });
|
|
13650
16111
|
const storage = options?.storage ?? new FilesystemStorage(
|
|
13651
16112
|
`${config.storage_path}/state`
|
|
@@ -14111,18 +16572,89 @@ async function createSanctuaryServer(options) {
|
|
|
14111
16572
|
...dashboardTools,
|
|
14112
16573
|
manifestTool
|
|
14113
16574
|
];
|
|
16575
|
+
let clientManager;
|
|
16576
|
+
let proxyRouter;
|
|
16577
|
+
const governor = new CallGovernor();
|
|
16578
|
+
const { tools: governorTools } = createGovernorTools(governor, auditLog);
|
|
16579
|
+
allTools.push(...governorTools);
|
|
16580
|
+
const profile = profileStore.get();
|
|
16581
|
+
if (profile.upstream_servers && profile.upstream_servers.length > 0) {
|
|
16582
|
+
const enabledServers = profile.upstream_servers.filter((s) => s.enabled);
|
|
16583
|
+
if (enabledServers.length > 0) {
|
|
16584
|
+
clientManager = new ClientManager({
|
|
16585
|
+
onStateChange: (serverName, state, toolCount, error) => {
|
|
16586
|
+
if (dashboard) {
|
|
16587
|
+
dashboard.broadcastSSE("proxy-server-status", {
|
|
16588
|
+
server: serverName,
|
|
16589
|
+
state,
|
|
16590
|
+
tool_count: toolCount,
|
|
16591
|
+
error,
|
|
16592
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
16593
|
+
});
|
|
16594
|
+
}
|
|
16595
|
+
auditLog.append("l2", `proxy_server_${state}`, "system", {
|
|
16596
|
+
server: serverName,
|
|
16597
|
+
tool_count: toolCount,
|
|
16598
|
+
error
|
|
16599
|
+
});
|
|
16600
|
+
}
|
|
16601
|
+
});
|
|
16602
|
+
proxyRouter = new ProxyRouter(
|
|
16603
|
+
clientManager,
|
|
16604
|
+
injectionDetector,
|
|
16605
|
+
auditLog,
|
|
16606
|
+
{
|
|
16607
|
+
contextGateFilter: async (_toolName, args) => {
|
|
16608
|
+
const activeProfile = profileStore.get();
|
|
16609
|
+
if (activeProfile.features.context_gating.enabled) {
|
|
16610
|
+
return args;
|
|
16611
|
+
}
|
|
16612
|
+
return args;
|
|
16613
|
+
},
|
|
16614
|
+
governor
|
|
16615
|
+
}
|
|
16616
|
+
);
|
|
16617
|
+
clientManager.configure(enabledServers).catch((err) => {
|
|
16618
|
+
console.error(`[Sanctuary] Failed to configure upstream servers: ${err instanceof Error ? err.message : "unknown error"}`);
|
|
16619
|
+
});
|
|
16620
|
+
await new Promise((resolve) => setTimeout(resolve, 2e3));
|
|
16621
|
+
const proxiedTools = proxyRouter.getProxiedTools();
|
|
16622
|
+
if (proxiedTools.length > 0) {
|
|
16623
|
+
allTools.push(...proxiedTools);
|
|
16624
|
+
}
|
|
16625
|
+
if (dashboard) {
|
|
16626
|
+
dashboard.setDependencies({
|
|
16627
|
+
policy,
|
|
16628
|
+
baseline,
|
|
16629
|
+
auditLog,
|
|
16630
|
+
clientManager
|
|
16631
|
+
});
|
|
16632
|
+
}
|
|
16633
|
+
}
|
|
16634
|
+
}
|
|
14114
16635
|
allTools = allTools.map((tool) => ({
|
|
14115
16636
|
...tool,
|
|
14116
16637
|
handler: contextGateEnforcer.wrapHandler(tool.name, tool.handler)
|
|
14117
16638
|
}));
|
|
16639
|
+
if (proxyRouter) {
|
|
16640
|
+
gate.setProxyTierResolver((toolName) => {
|
|
16641
|
+
const parsed = ProxyRouter.parseProxyToolName(toolName);
|
|
16642
|
+
if (!parsed) return null;
|
|
16643
|
+
return proxyRouter.getTierForTool(parsed.serverName, parsed.toolName);
|
|
16644
|
+
});
|
|
16645
|
+
}
|
|
14118
16646
|
const server = createServer(allTools, { gate });
|
|
14119
16647
|
await saveConfig(config);
|
|
14120
|
-
const
|
|
16648
|
+
const cleanup = () => {
|
|
14121
16649
|
baseline.save().catch(() => {
|
|
14122
16650
|
});
|
|
16651
|
+
if (clientManager) {
|
|
16652
|
+
clientManager.shutdown().catch(() => {
|
|
16653
|
+
});
|
|
16654
|
+
}
|
|
14123
16655
|
};
|
|
14124
|
-
process.on("SIGINT",
|
|
14125
|
-
process.on("SIGTERM",
|
|
16656
|
+
process.on("SIGINT", cleanup);
|
|
16657
|
+
process.on("SIGTERM", cleanup);
|
|
14126
16658
|
if (recoveryKey) {
|
|
14127
16659
|
console.error(
|
|
14128
16660
|
`\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
|