@sanctuary-framework/mcp-server 0.4.2 → 0.5.1

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.js CHANGED
@@ -256,7 +256,18 @@ function defaultConfig() {
256
256
  };
257
257
  }
258
258
  async function loadConfig(configPath) {
259
- const config = defaultConfig();
259
+ let config = defaultConfig();
260
+ const storagePath = process.env.SANCTUARY_STORAGE_PATH ?? config.storage_path;
261
+ const path = configPath ?? join(storagePath, "sanctuary.json");
262
+ try {
263
+ const raw = await readFile(path, "utf-8");
264
+ const fileConfig = JSON.parse(raw);
265
+ config = deepMerge(config, fileConfig);
266
+ } catch (err) {
267
+ if (err instanceof Error && err.message.includes("unimplemented features")) {
268
+ throw err;
269
+ }
270
+ }
260
271
  if (process.env.SANCTUARY_STORAGE_PATH) {
261
272
  config.storage_path = process.env.SANCTUARY_STORAGE_PATH;
262
273
  }
@@ -269,6 +280,9 @@ async function loadConfig(configPath) {
269
280
  if (process.env.SANCTUARY_DASHBOARD_ENABLED === "true") {
270
281
  config.dashboard.enabled = true;
271
282
  }
283
+ if (process.env.SANCTUARY_DASHBOARD_ENABLED === "false") {
284
+ config.dashboard.enabled = false;
285
+ }
272
286
  if (process.env.SANCTUARY_DASHBOARD_PORT) {
273
287
  config.dashboard.port = parseInt(process.env.SANCTUARY_DASHBOARD_PORT, 10);
274
288
  }
@@ -287,6 +301,9 @@ async function loadConfig(configPath) {
287
301
  if (process.env.SANCTUARY_WEBHOOK_ENABLED === "true") {
288
302
  config.webhook.enabled = true;
289
303
  }
304
+ if (process.env.SANCTUARY_WEBHOOK_ENABLED === "false") {
305
+ config.webhook.enabled = false;
306
+ }
290
307
  if (process.env.SANCTUARY_WEBHOOK_URL) {
291
308
  config.webhook.url = process.env.SANCTUARY_WEBHOOK_URL;
292
309
  }
@@ -299,19 +316,9 @@ async function loadConfig(configPath) {
299
316
  if (process.env.SANCTUARY_WEBHOOK_CALLBACK_HOST) {
300
317
  config.webhook.callback_host = process.env.SANCTUARY_WEBHOOK_CALLBACK_HOST;
301
318
  }
302
- const path = configPath ?? join(config.storage_path, "sanctuary.json");
303
- try {
304
- const raw = await readFile(path, "utf-8");
305
- const fileConfig = JSON.parse(raw);
306
- const merged = deepMerge(config, fileConfig);
307
- validateConfig(merged);
308
- return merged;
309
- } catch (err) {
310
- if (err instanceof Error && err.message.includes("unimplemented features")) {
311
- throw err;
312
- }
313
- return config;
314
- }
319
+ config.version = PKG_VERSION;
320
+ validateConfig(config);
321
+ return config;
315
322
  }
316
323
  async function saveConfig(config, configPath) {
317
324
  const path = join(config.storage_path, "sanctuary.json");
@@ -4039,648 +4046,1478 @@ function generateDashboardHTML(options) {
4039
4046
  <meta charset="utf-8">
4040
4047
  <meta name="viewport" content="width=device-width, initial-scale=1">
4041
4048
  <title>Sanctuary \u2014 Principal Dashboard</title>
4049
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
4042
4050
  <style>
4043
4051
  :root {
4044
- --bg: #0f1117;
4045
- --bg-surface: #1a1d27;
4046
- --bg-elevated: #242736;
4047
- --border: #2e3244;
4048
- --text: #e4e6f0;
4049
- --text-muted: #8b8fa3;
4050
- --accent: #6c8aff;
4051
- --accent-hover: #839dff;
4052
- --approve: #3ecf8e;
4053
- --approve-hover: #5dd9a3;
4054
- --deny: #f87171;
4055
- --deny-hover: #fca5a5;
4056
- --warning: #fbbf24;
4057
- --tier1: #f87171;
4058
- --tier2: #fbbf24;
4059
- --tier3: #3ecf8e;
4060
- --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
4061
- --mono: "SF Mono", "Fira Code", "Cascadia Code", monospace;
4062
- --radius: 8px;
4063
- }
4064
-
4065
- * { box-sizing: border-box; margin: 0; padding: 0; }
4052
+ --bg: #0d1117;
4053
+ --surface: #161b22;
4054
+ --border: #30363d;
4055
+ --text-primary: #e6edf3;
4056
+ --text-secondary: #8b949e;
4057
+ --green: #3fb950;
4058
+ --amber: #d29922;
4059
+ --red: #f85149;
4060
+ --blue: #58a6ff;
4061
+ --mono: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
4062
+ --sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
4063
+ --radius: 6px;
4064
+ }
4065
+
4066
+ * {
4067
+ box-sizing: border-box;
4068
+ margin: 0;
4069
+ padding: 0;
4070
+ }
4071
+
4072
+ html, body {
4073
+ width: 100%;
4074
+ height: 100%;
4075
+ overflow: hidden;
4076
+ }
4077
+
4066
4078
  body {
4067
- font-family: var(--font);
4079
+ font-family: var(--sans);
4068
4080
  background: var(--bg);
4069
- color: var(--text);
4070
- line-height: 1.5;
4071
- min-height: 100vh;
4081
+ color: var(--text-primary);
4082
+ display: flex;
4083
+ flex-direction: column;
4072
4084
  }
4073
4085
 
4074
- /* Layout */
4075
- .container { max-width: 960px; margin: 0 auto; padding: 24px 16px; }
4086
+ /* \u2500\u2500 Top Status Bar (fixed) \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 */
4076
4087
 
4077
- header {
4078
- display: flex; align-items: center; justify-content: space-between;
4079
- padding-bottom: 20px; border-bottom: 1px solid var(--border);
4080
- margin-bottom: 24px;
4088
+ .status-bar {
4089
+ position: fixed;
4090
+ top: 0;
4091
+ left: 0;
4092
+ right: 0;
4093
+ height: 56px;
4094
+ background: var(--surface);
4095
+ border-bottom: 1px solid var(--border);
4096
+ display: flex;
4097
+ align-items: center;
4098
+ padding: 0 20px;
4099
+ gap: 24px;
4100
+ z-index: 1000;
4081
4101
  }
4082
- header h1 { font-size: 20px; font-weight: 600; letter-spacing: -0.3px; }
4083
- header h1 span { color: var(--accent); }
4084
- .status-badge {
4085
- display: inline-flex; align-items: center; gap: 6px;
4086
- font-size: 12px; color: var(--text-muted);
4087
- padding: 4px 10px; border-radius: 12px;
4088
- background: var(--bg-surface); border: 1px solid var(--border);
4102
+
4103
+ .status-bar-left {
4104
+ display: flex;
4105
+ align-items: center;
4106
+ gap: 12px;
4107
+ flex: 0 0 auto;
4089
4108
  }
4090
- .status-dot {
4091
- width: 8px; height: 8px; border-radius: 50%;
4092
- background: var(--approve); animation: pulse 2s infinite;
4093
- }
4094
- .status-dot.disconnected { background: var(--deny); animation: none; }
4095
- @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
4096
-
4097
- /* Tabs */
4098
- .tabs {
4099
- display: flex; gap: 2px; margin-bottom: 20px;
4100
- background: var(--bg-surface); border-radius: var(--radius);
4101
- padding: 3px; border: 1px solid var(--border);
4102
- }
4103
- .tab {
4104
- flex: 1; padding: 8px 12px; text-align: center;
4105
- font-size: 13px; font-weight: 500; cursor: pointer;
4106
- border-radius: 6px; border: none; color: var(--text-muted);
4107
- background: transparent; transition: all 0.15s;
4108
- }
4109
- .tab:hover { color: var(--text); }
4110
- .tab.active { background: var(--bg-elevated); color: var(--text); }
4111
- .tab .count {
4112
- display: inline-flex; align-items: center; justify-content: center;
4113
- min-width: 18px; height: 18px; padding: 0 5px;
4114
- font-size: 11px; font-weight: 600; border-radius: 9px;
4115
- margin-left: 6px;
4116
- }
4117
- .tab .count.alert { background: var(--deny); color: white; }
4118
- .tab .count.muted { background: var(--border); color: var(--text-muted); }
4119
-
4120
- /* Tab Content */
4121
- .tab-content { display: none; }
4122
- .tab-content.active { display: block; }
4123
-
4124
- /* Pending Requests */
4125
- .pending-empty {
4126
- text-align: center; padding: 60px 20px; color: var(--text-muted);
4127
- }
4128
- .pending-empty .icon { font-size: 32px; margin-bottom: 12px; }
4129
- .pending-empty p { font-size: 14px; }
4130
-
4131
- .request-card {
4132
- background: var(--bg-surface); border: 1px solid var(--border);
4133
- border-radius: var(--radius); padding: 16px; margin-bottom: 12px;
4134
- animation: slideIn 0.2s ease-out;
4135
- }
4136
- @keyframes slideIn { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }
4137
- .request-card.tier1 { border-left: 3px solid var(--tier1); }
4138
- .request-card.tier2 { border-left: 3px solid var(--tier2); }
4139
- .request-header {
4140
- display: flex; align-items: center; justify-content: space-between;
4141
- margin-bottom: 10px;
4142
- }
4143
- .request-op {
4144
- font-family: var(--mono); font-size: 14px; font-weight: 600;
4145
- }
4146
- .tier-badge {
4147
- font-size: 11px; font-weight: 600; padding: 2px 8px;
4148
- border-radius: 4px; text-transform: uppercase;
4149
- }
4150
- .tier-badge.tier1 { background: rgba(248,113,113,0.15); color: var(--tier1); }
4151
- .tier-badge.tier2 { background: rgba(251,191,36,0.15); color: var(--tier2); }
4152
- .request-reason {
4153
- font-size: 13px; color: var(--text-muted); margin-bottom: 12px;
4154
- }
4155
- .request-context {
4156
- font-family: var(--mono); font-size: 12px; color: var(--text-muted);
4157
- background: var(--bg); border-radius: 4px; padding: 8px 10px;
4158
- margin-bottom: 14px; white-space: pre-wrap; word-break: break-all;
4159
- max-height: 120px; overflow-y: auto;
4160
- }
4161
- .request-actions {
4162
- display: flex; align-items: center; gap: 10px;
4109
+
4110
+ .sanctuary-logo {
4111
+ font-weight: 700;
4112
+ font-size: 16px;
4113
+ letter-spacing: -0.5px;
4114
+ color: var(--text-primary);
4163
4115
  }
4164
- .btn {
4165
- padding: 7px 16px; border-radius: 6px; font-size: 13px;
4166
- font-weight: 600; border: none; cursor: pointer;
4167
- transition: all 0.15s;
4116
+
4117
+ .sanctuary-logo span {
4118
+ color: var(--blue);
4168
4119
  }
4169
- .btn-approve { background: var(--approve); color: #0f1117; }
4170
- .btn-approve:hover { background: var(--approve-hover); }
4171
- .btn-deny { background: var(--deny); color: white; }
4172
- .btn-deny:hover { background: var(--deny-hover); }
4173
- .countdown {
4174
- margin-left: auto; font-size: 12px; color: var(--text-muted);
4120
+
4121
+ .version {
4122
+ font-size: 11px;
4123
+ color: var(--text-secondary);
4175
4124
  font-family: var(--mono);
4176
4125
  }
4177
- .countdown.urgent { color: var(--deny); font-weight: 600; }
4178
4126
 
4179
- /* Audit Log */
4180
- .audit-table { width: 100%; border-collapse: collapse; }
4181
- .audit-table th {
4182
- text-align: left; font-size: 11px; font-weight: 600;
4183
- text-transform: uppercase; letter-spacing: 0.5px;
4184
- color: var(--text-muted); padding: 8px 10px;
4185
- border-bottom: 1px solid var(--border);
4127
+ .status-bar-center {
4128
+ flex: 1;
4129
+ display: flex;
4130
+ align-items: center;
4131
+ justify-content: center;
4186
4132
  }
4187
- .audit-table td {
4188
- font-size: 13px; padding: 8px 10px;
4189
- border-bottom: 1px solid var(--border);
4133
+
4134
+ .sovereignty-badge {
4135
+ display: flex;
4136
+ align-items: center;
4137
+ gap: 8px;
4138
+ padding: 6px 12px;
4139
+ background: rgba(88, 166, 255, 0.1);
4140
+ border: 1px solid var(--blue);
4141
+ border-radius: 20px;
4142
+ font-size: 13px;
4143
+ font-weight: 600;
4190
4144
  }
4191
- .audit-table tr { transition: background 0.1s; }
4192
- .audit-table tr:hover { background: var(--bg-elevated); }
4193
- .audit-table tr.new { animation: highlight 1s ease-out; }
4194
- @keyframes highlight { from { background: rgba(108,138,255,0.15); } to { background: transparent; } }
4195
- .audit-time { font-family: var(--mono); font-size: 12px; color: var(--text-muted); }
4196
- .audit-op { font-family: var(--mono); font-size: 12px; }
4197
- .audit-layer {
4198
- font-size: 11px; font-weight: 600; padding: 1px 6px;
4199
- border-radius: 3px; text-transform: uppercase;
4200
- }
4201
- .audit-layer.l1 { background: rgba(108,138,255,0.15); color: var(--accent); }
4202
- .audit-layer.l2 { background: rgba(251,191,36,0.15); color: var(--tier2); }
4203
- .audit-layer.l3 { background: rgba(62,207,142,0.15); color: var(--tier3); }
4204
- .audit-layer.l4 { background: rgba(168,85,247,0.15); color: #a855f7; }
4205
-
4206
- /* Baseline & Policy */
4207
- .info-section {
4208
- background: var(--bg-surface); border: 1px solid var(--border);
4209
- border-radius: var(--radius); padding: 16px; margin-bottom: 16px;
4210
- }
4211
- .info-section h3 {
4212
- font-size: 13px; font-weight: 600; text-transform: uppercase;
4213
- letter-spacing: 0.5px; color: var(--text-muted); margin-bottom: 12px;
4214
- }
4215
- .info-row {
4216
- display: flex; justify-content: space-between; align-items: center;
4217
- padding: 6px 0; font-size: 13px;
4218
- }
4219
- .info-label { color: var(--text-muted); }
4220
- .info-value { font-family: var(--mono); font-size: 12px; }
4221
- .tag-list { display: flex; flex-wrap: wrap; gap: 4px; }
4222
- .tag {
4223
- font-family: var(--mono); font-size: 11px; padding: 2px 8px;
4224
- background: var(--bg-elevated); border-radius: 4px;
4225
- color: var(--text-muted); border: 1px solid var(--border);
4226
- }
4227
- .policy-op {
4228
- font-family: var(--mono); font-size: 12px; padding: 3px 0;
4229
- }
4230
-
4231
- /* Footer */
4232
- footer {
4233
- margin-top: 32px; padding-top: 16px;
4234
- border-top: 1px solid var(--border);
4235
- font-size: 12px; color: var(--text-muted);
4236
- text-align: center;
4145
+
4146
+ .sovereignty-score {
4147
+ display: flex;
4148
+ align-items: center;
4149
+ justify-content: center;
4150
+ width: 28px;
4151
+ height: 28px;
4152
+ border-radius: 50%;
4153
+ font-family: var(--mono);
4154
+ font-weight: 700;
4155
+ font-size: 12px;
4156
+ background: var(--blue);
4157
+ color: var(--bg);
4237
4158
  }
4238
- </style>
4239
- </head>
4240
- <body>
4241
- <div class="container">
4242
- <header>
4243
- <h1><span>Sanctuary</span> Principal Dashboard</h1>
4244
- <div class="status-badge">
4245
- <div class="status-dot" id="statusDot"></div>
4246
- <span id="statusText">Connected</span>
4247
- </div>
4248
- </header>
4249
-
4250
- <div class="tabs">
4251
- <button class="tab active" data-tab="pending">
4252
- Pending<span class="count muted" id="pendingCount">0</span>
4253
- </button>
4254
- <button class="tab" data-tab="audit">
4255
- Audit Log<span class="count muted" id="auditCount">0</span>
4256
- </button>
4257
- <button class="tab" data-tab="baseline">Baseline</button>
4258
- <button class="tab" data-tab="policy">Policy</button>
4259
- </div>
4260
4159
 
4261
- <!-- Pending Approvals -->
4262
- <div class="tab-content active" id="tab-pending">
4263
- <div class="pending-empty" id="pendingEmpty">
4264
- <div class="icon">&#x2714;</div>
4265
- <p>No pending approval requests.</p>
4266
- <p style="font-size:12px; margin-top:4px;">Requests will appear here in real time.</p>
4267
- </div>
4268
- <div id="pendingList"></div>
4269
- </div>
4160
+ .sovereignty-score.high {
4161
+ background: var(--green);
4162
+ }
4270
4163
 
4271
- <!-- Audit Log -->
4272
- <div class="tab-content" id="tab-audit">
4273
- <table class="audit-table">
4274
- <thead>
4275
- <tr><th>Time</th><th>Layer</th><th>Operation</th><th>Identity</th></tr>
4276
- </thead>
4277
- <tbody id="auditBody"></tbody>
4278
- </table>
4279
- </div>
4164
+ .sovereignty-score.medium {
4165
+ background: var(--amber);
4166
+ }
4280
4167
 
4281
- <!-- Baseline -->
4282
- <div class="tab-content" id="tab-baseline">
4283
- <div class="info-section">
4284
- <h3>Session Info</h3>
4285
- <div class="info-row"><span class="info-label">First session</span><span class="info-value" id="bFirstSession">\u2014</span></div>
4286
- <div class="info-row"><span class="info-label">Started</span><span class="info-value" id="bStarted">\u2014</span></div>
4287
- </div>
4288
- <div class="info-section">
4289
- <h3>Known Namespaces</h3>
4290
- <div class="tag-list" id="bNamespaces"><span class="tag">\u2014</span></div>
4291
- </div>
4292
- <div class="info-section">
4293
- <h3>Known Counterparties</h3>
4294
- <div class="tag-list" id="bCounterparties"><span class="tag">\u2014</span></div>
4295
- </div>
4296
- <div class="info-section">
4297
- <h3>Tool Call Counts</h3>
4298
- <div id="bToolCalls"><span class="info-value">\u2014</span></div>
4299
- </div>
4300
- </div>
4168
+ .sovereignty-score.low {
4169
+ background: var(--red);
4170
+ }
4301
4171
 
4302
- <!-- Policy -->
4303
- <div class="tab-content" id="tab-policy">
4304
- <div class="info-section">
4305
- <h3>Tier 1 \u2014 Always Requires Approval</h3>
4306
- <div id="pTier1"></div>
4307
- </div>
4308
- <div class="info-section">
4309
- <h3>Tier 2 \u2014 Anomaly Detection</h3>
4310
- <div id="pTier2"></div>
4311
- </div>
4312
- <div class="info-section">
4313
- <h3>Tier 3 \u2014 Always Allowed</h3>
4314
- <div class="info-row">
4315
- <span class="info-label">Operations</span>
4316
- <span class="info-value" id="pTier3Count">\u2014</span>
4317
- </div>
4318
- </div>
4319
- <div class="info-section">
4320
- <h3>Approval Channel</h3>
4321
- <div id="pChannel"></div>
4322
- </div>
4323
- </div>
4172
+ .status-bar-right {
4173
+ display: flex;
4174
+ align-items: center;
4175
+ gap: 16px;
4176
+ flex: 0 0 auto;
4177
+ }
4324
4178
 
4325
- <footer>Sanctuary Framework v${options.serverVersion} \u2014 Principal Dashboard</footer>
4326
- </div>
4179
+ .protections-indicator {
4180
+ display: flex;
4181
+ align-items: center;
4182
+ gap: 6px;
4183
+ font-size: 12px;
4184
+ color: var(--text-secondary);
4185
+ font-family: var(--mono);
4186
+ }
4327
4187
 
4328
- <script>
4329
- (function() {
4330
- const TIMEOUT = ${options.timeoutSeconds};
4331
- // SEC-012: Auth token is passed via Authorization header only \u2014 never in URLs.
4332
- // The token is provided by the server at generation time (embedded for initial auth).
4333
- const AUTH_TOKEN = ${options.authToken ? JSON.stringify(options.authToken) : "null"};
4334
- let SESSION_ID = null; // Short-lived session for SSE and URL-based requests
4335
- const pending = new Map();
4336
- let auditCount = 0;
4188
+ .protections-indicator .count {
4189
+ color: var(--text-primary);
4190
+ font-weight: 600;
4191
+ }
4337
4192
 
4338
- // Auth helpers \u2014 SEC-012: token goes in header, session goes in URL
4339
- function authHeaders() {
4340
- const h = { 'Content-Type': 'application/json' };
4341
- if (AUTH_TOKEN) h['Authorization'] = 'Bearer ' + AUTH_TOKEN;
4342
- return h;
4193
+ .uptime {
4194
+ display: flex;
4195
+ align-items: center;
4196
+ gap: 6px;
4197
+ font-size: 12px;
4198
+ color: var(--text-secondary);
4199
+ font-family: var(--mono);
4343
4200
  }
4344
- function sessionQuery(url) {
4345
- if (!SESSION_ID) return url;
4346
- const sep = url.includes('?') ? '&' : '?';
4347
- return url + sep + 'session=' + SESSION_ID;
4201
+
4202
+ .status-dot {
4203
+ width: 8px;
4204
+ height: 8px;
4205
+ border-radius: 50%;
4206
+ background: var(--green);
4207
+ animation: pulse 2s ease-in-out infinite;
4348
4208
  }
4349
4209
 
4350
- // SEC-012: Exchange the long-lived token for a short-lived session
4351
- async function exchangeSession() {
4352
- if (!AUTH_TOKEN) return;
4353
- try {
4354
- const resp = await fetch('/auth/session', { method: 'POST', headers: authHeaders() });
4355
- if (resp.ok) {
4356
- const data = await resp.json();
4357
- SESSION_ID = data.session_id;
4358
- // Refresh session before expiry (at 80% of TTL)
4359
- const refreshMs = (data.expires_in_seconds || 300) * 800;
4360
- setTimeout(async () => { await exchangeSession(); reconnectSSE(); }, refreshMs);
4361
- }
4362
- } catch(e) { /* will retry on next connect */ }
4210
+ .status-dot.disconnected {
4211
+ background: var(--red);
4212
+ animation: none;
4363
4213
  }
4364
4214
 
4365
- // Tab switching
4366
- document.querySelectorAll('.tab').forEach(tab => {
4367
- tab.addEventListener('click', () => {
4368
- document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
4369
- document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
4370
- tab.classList.add('active');
4371
- document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
4372
- });
4373
- });
4215
+ @keyframes pulse {
4216
+ 0%, 100% { opacity: 1; }
4217
+ 50% { opacity: 0.5; }
4218
+ }
4374
4219
 
4375
- // SSE Connection \u2014 SEC-012: uses short-lived session token in URL, not auth token
4376
- let evtSource;
4377
- function reconnectSSE() {
4378
- if (evtSource) { evtSource.close(); }
4379
- connect();
4220
+ .pending-badge {
4221
+ display: inline-flex;
4222
+ align-items: center;
4223
+ justify-content: center;
4224
+ min-width: 24px;
4225
+ height: 24px;
4226
+ padding: 0 6px;
4227
+ background: var(--red);
4228
+ color: white;
4229
+ border-radius: 12px;
4230
+ font-size: 11px;
4231
+ font-weight: 700;
4232
+ animation: pulse 1s ease-in-out infinite;
4380
4233
  }
4381
- function connect() {
4382
- evtSource = new EventSource(sessionQuery('/events'));
4383
- evtSource.onopen = () => {
4384
- document.getElementById('statusDot').classList.remove('disconnected');
4385
- document.getElementById('statusText').textContent = 'Connected';
4386
- };
4387
- evtSource.onerror = () => {
4388
- document.getElementById('statusDot').classList.add('disconnected');
4389
- document.getElementById('statusText').textContent = 'Reconnecting...';
4390
- };
4391
- evtSource.addEventListener('pending-request', (e) => {
4392
- const data = JSON.parse(e.data);
4393
- addPendingRequest(data);
4394
- });
4395
- evtSource.addEventListener('request-resolved', (e) => {
4396
- const data = JSON.parse(e.data);
4397
- removePendingRequest(data.request_id);
4398
- });
4399
- evtSource.addEventListener('audit-entry', (e) => {
4400
- const data = JSON.parse(e.data);
4401
- addAuditEntry(data);
4402
- });
4403
- evtSource.addEventListener('baseline-update', (e) => {
4404
- const data = JSON.parse(e.data);
4405
- updateBaseline(data);
4406
- });
4407
- evtSource.addEventListener('policy-update', (e) => {
4408
- const data = JSON.parse(e.data);
4409
- updatePolicy(data);
4410
- });
4411
- evtSource.addEventListener('init', (e) => {
4412
- const data = JSON.parse(e.data);
4413
- if (data.baseline) updateBaseline(data.baseline);
4414
- if (data.policy) updatePolicy(data.policy);
4415
- if (data.pending) data.pending.forEach(addPendingRequest);
4416
- if (data.audit) data.audit.forEach(addAuditEntry);
4417
- });
4234
+
4235
+ .pending-badge.hidden {
4236
+ display: none;
4418
4237
  }
4419
4238
 
4420
- // Pending requests
4421
- function addPendingRequest(req) {
4422
- pending.set(req.request_id, { ...req, remaining: TIMEOUT });
4423
- renderPending();
4424
- updatePendingCount();
4425
- flashTab('pending');
4239
+ /* \u2500\u2500 Main Layout \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 */
4240
+
4241
+ .main-container {
4242
+ flex: 1;
4243
+ display: flex;
4244
+ margin-top: 56px;
4245
+ overflow: hidden;
4426
4246
  }
4427
4247
 
4428
- function removePendingRequest(id) {
4429
- pending.delete(id);
4430
- renderPending();
4431
- updatePendingCount();
4248
+ .activity-feed {
4249
+ flex: 3;
4250
+ display: flex;
4251
+ flex-direction: column;
4252
+ border-right: 1px solid var(--border);
4253
+ overflow: hidden;
4432
4254
  }
4433
4255
 
4434
- function renderPending() {
4435
- const list = document.getElementById('pendingList');
4436
- const empty = document.getElementById('pendingEmpty');
4437
- if (pending.size === 0) {
4438
- list.innerHTML = '';
4439
- empty.style.display = 'block';
4440
- return;
4441
- }
4442
- empty.style.display = 'none';
4443
- list.innerHTML = '';
4444
- for (const [id, req] of pending) {
4445
- const card = document.createElement('div');
4446
- card.className = 'request-card tier' + req.tier;
4447
- card.id = 'req-' + id;
4448
- const ctx = typeof req.context === 'string' ? req.context : JSON.stringify(req.context, null, 2);
4449
- card.innerHTML =
4450
- '<div class="request-header">' +
4451
- '<span class="request-op">' + esc(req.operation) + '</span>' +
4452
- '<span class="tier-badge tier' + req.tier + '">Tier ' + req.tier + '</span>' +
4453
- '</div>' +
4454
- '<div class="request-reason">' + esc(req.reason) + '</div>' +
4455
- '<div class="request-context">' + esc(ctx) + '</div>' +
4456
- '<div class="request-actions">' +
4457
- '<button class="btn btn-approve" onclick="handleApprove(\\'' + id + '\\')">Approve</button>' +
4458
- '<button class="btn btn-deny" onclick="handleDeny(\\'' + id + '\\')">Deny</button>' +
4459
- '<span class="countdown" id="cd-' + id + '">' + req.remaining + 's</span>' +
4460
- '</div>';
4461
- list.appendChild(card);
4462
- }
4256
+ .feed-header {
4257
+ padding: 16px 20px;
4258
+ border-bottom: 1px solid var(--border);
4259
+ display: flex;
4260
+ align-items: center;
4261
+ gap: 8px;
4262
+ font-size: 12px;
4263
+ font-weight: 600;
4264
+ text-transform: uppercase;
4265
+ letter-spacing: 0.5px;
4266
+ color: var(--text-secondary);
4463
4267
  }
4464
4268
 
4465
- function updatePendingCount() {
4466
- const el = document.getElementById('pendingCount');
4467
- el.textContent = pending.size;
4468
- el.className = pending.size > 0 ? 'count alert' : 'count muted';
4269
+ .feed-header-dot {
4270
+ width: 6px;
4271
+ height: 6px;
4272
+ border-radius: 50%;
4273
+ background: var(--green);
4469
4274
  }
4470
4275
 
4471
- function flashTab(name) {
4472
- const tab = document.querySelector('[data-tab="' + name + '"]');
4473
- if (!tab.classList.contains('active')) {
4474
- tab.style.background = 'rgba(248,113,113,0.15)';
4475
- setTimeout(() => { tab.style.background = ''; }, 1500);
4476
- }
4276
+ .activity-list {
4277
+ flex: 1;
4278
+ overflow-y: auto;
4279
+ overflow-x: hidden;
4477
4280
  }
4478
4281
 
4479
- // Countdown timer
4480
- setInterval(() => {
4481
- for (const [id, req] of pending) {
4482
- req.remaining = Math.max(0, req.remaining - 1);
4483
- const el = document.getElementById('cd-' + id);
4484
- if (el) {
4485
- el.textContent = req.remaining + 's';
4486
- el.className = req.remaining <= 30 ? 'countdown urgent' : 'countdown';
4487
- }
4488
- }
4489
- }, 1000);
4282
+ .activity-item {
4283
+ padding: 12px 20px;
4284
+ border-bottom: 1px solid rgba(48, 54, 61, 0.5);
4285
+ font-size: 13px;
4286
+ font-family: var(--mono);
4287
+ cursor: pointer;
4288
+ transition: background 0.15s;
4289
+ display: flex;
4290
+ align-items: flex-start;
4291
+ gap: 10px;
4292
+ }
4490
4293
 
4491
- // Approve / Deny handlers (global scope)
4492
- window.handleApprove = function(id) {
4493
- fetch('/api/approve/' + id, { method: 'POST', headers: authHeaders() }).then(() => {
4494
- removePendingRequest(id);
4495
- });
4496
- };
4497
- window.handleDeny = function(id) {
4498
- fetch('/api/deny/' + id, { method: 'POST', headers: authHeaders() }).then(() => {
4499
- removePendingRequest(id);
4500
- });
4501
- };
4294
+ .activity-item:hover {
4295
+ background: rgba(88, 166, 255, 0.05);
4296
+ }
4502
4297
 
4503
- // Audit log
4504
- function addAuditEntry(entry) {
4505
- auditCount++;
4506
- document.getElementById('auditCount').textContent = auditCount;
4507
- const tbody = document.getElementById('auditBody');
4508
- const tr = document.createElement('tr');
4509
- tr.className = 'new';
4510
- const time = entry.timestamp ? new Date(entry.timestamp).toLocaleTimeString() : '\u2014';
4511
- const layer = entry.layer || '\u2014';
4512
- tr.innerHTML =
4513
- '<td class="audit-time">' + esc(time) + '</td>' +
4514
- '<td><span class="audit-layer ' + layer + '">' + esc(layer) + '</span></td>' +
4515
- '<td class="audit-op">' + esc(entry.operation || '\u2014') + '</td>' +
4516
- '<td style="font-size:12px;color:var(--text-muted)">' + esc(entry.identity_id || '\u2014') + '</td>';
4517
- tbody.insertBefore(tr, tbody.firstChild);
4518
- // Keep last 100 entries
4519
- while (tbody.children.length > 100) tbody.removeChild(tbody.lastChild);
4520
- }
4521
-
4522
- // Baseline
4523
- function updateBaseline(b) {
4524
- if (!b) return;
4525
- document.getElementById('bFirstSession').textContent = b.is_first_session ? 'Yes' : 'No';
4526
- document.getElementById('bStarted').textContent = b.started_at ? new Date(b.started_at).toLocaleString() : '\u2014';
4527
- const ns = document.getElementById('bNamespaces');
4528
- ns.innerHTML = (b.known_namespaces || []).length > 0
4529
- ? (b.known_namespaces || []).map(n => '<span class="tag">' + esc(n) + '</span>').join('')
4530
- : '<span class="tag">none</span>';
4531
- const cp = document.getElementById('bCounterparties');
4532
- cp.innerHTML = (b.known_counterparties || []).length > 0
4533
- ? (b.known_counterparties || []).map(c => '<span class="tag">' + esc(c.slice(0,16)) + '...</span>').join('')
4534
- : '<span class="tag">none</span>';
4535
- const tc = document.getElementById('bToolCalls');
4536
- const counts = b.tool_call_counts || {};
4537
- const entries = Object.entries(counts).sort((a,b) => b[1] - a[1]);
4538
- tc.innerHTML = entries.length > 0
4539
- ? entries.map(([k,v]) => '<div class="info-row"><span class="info-label">' + esc(k) + '</span><span class="info-value">' + v + '</span></div>').join('')
4540
- : '<span class="info-value">no calls yet</span>';
4541
- }
4542
-
4543
- // Policy
4544
- function updatePolicy(p) {
4545
- if (!p) return;
4546
- const t1 = document.getElementById('pTier1');
4547
- t1.innerHTML = (p.tier1_always_approve || []).map(op =>
4548
- '<div class="policy-op">' + esc(op) + '</div>'
4549
- ).join('');
4550
- const t2 = document.getElementById('pTier2');
4551
- const cfg = p.tier2_anomaly || {};
4552
- t2.innerHTML = Object.entries(cfg).map(([k,v]) =>
4553
- '<div class="info-row"><span class="info-label">' + esc(k) + '</span><span class="info-value">' + esc(String(v)) + '</span></div>'
4554
- ).join('');
4555
- document.getElementById('pTier3Count').textContent = (p.tier3_always_allow || []).length + ' operations';
4556
- const ch = document.getElementById('pChannel');
4557
- const chan = p.approval_channel || {};
4558
- ch.innerHTML = Object.entries(chan).filter(([k]) => k !== 'webhook_secret').map(([k,v]) =>
4559
- '<div class="info-row"><span class="info-label">' + esc(k) + '</span><span class="info-value">' + esc(String(v)) + '</span></div>'
4560
- ).join('');
4298
+ .activity-item-icon {
4299
+ flex: 0 0 auto;
4300
+ width: 16px;
4301
+ text-align: center;
4302
+ font-size: 12px;
4303
+ color: var(--text-secondary);
4304
+ margin-top: 1px;
4561
4305
  }
4562
4306
 
4563
- function esc(s) {
4564
- if (!s) return '';
4565
- const d = document.createElement('div');
4566
- d.textContent = String(s);
4567
- return d.innerHTML;
4307
+ .activity-item-content {
4308
+ flex: 1;
4309
+ min-width: 0;
4568
4310
  }
4569
4311
 
4570
- // Init \u2014 SEC-012: exchange token for session before connecting SSE
4571
- (async function init() {
4572
- await exchangeSession();
4573
- // Clean token from URL if present (legacy bookmarks)
4574
- if (window.location.search.includes('token=')) {
4575
- const clean = window.location.pathname;
4576
- window.history.replaceState({}, '', clean);
4577
- }
4578
- connect();
4579
- fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4580
- if (data.baseline) updateBaseline(data.baseline);
4581
- if (data.policy) updatePolicy(data.policy);
4582
- }).catch(() => {});
4583
- })();
4584
- })();
4585
- </script>
4586
- </body>
4587
- </html>`;
4588
- }
4312
+ .activity-time {
4313
+ color: var(--text-secondary);
4314
+ font-size: 11px;
4315
+ margin-bottom: 2px;
4316
+ }
4589
4317
 
4590
- // src/principal-policy/dashboard.ts
4591
- var SESSION_TTL_MS = 5 * 60 * 1e3;
4592
- var MAX_SESSIONS = 1e3;
4593
- var RATE_LIMIT_WINDOW_MS = 6e4;
4594
- var RATE_LIMIT_GENERAL = 120;
4595
- var RATE_LIMIT_DECISIONS = 20;
4596
- var MAX_RATE_LIMIT_ENTRIES = 1e4;
4597
- var DashboardApprovalChannel = class {
4598
- config;
4599
- pending = /* @__PURE__ */ new Map();
4600
- sseClients = /* @__PURE__ */ new Set();
4601
- httpServer = null;
4602
- policy = null;
4603
- baseline = null;
4604
- auditLog = null;
4605
- dashboardHTML;
4606
- authToken;
4607
- useTLS;
4608
- /** SEC-012: Short-lived session store. Sessions replace URL query tokens. */
4609
- sessions = /* @__PURE__ */ new Map();
4610
- sessionCleanupTimer = null;
4611
- /** Rate limiting: per-IP request tracking */
4612
- rateLimits = /* @__PURE__ */ new Map();
4613
- constructor(config) {
4614
- this.config = config;
4615
- this.authToken = config.auth_token;
4616
- this.useTLS = !!(config.tls?.cert_path && config.tls?.key_path);
4617
- this.dashboardHTML = generateDashboardHTML({
4618
- timeoutSeconds: config.timeout_seconds,
4619
- serverVersion: SANCTUARY_VERSION,
4620
- authToken: this.authToken
4621
- });
4622
- this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
4318
+ .activity-main {
4319
+ display: flex;
4320
+ gap: 8px;
4321
+ align-items: baseline;
4322
+ margin-bottom: 4px;
4623
4323
  }
4624
- /**
4625
- * Inject dependencies after construction.
4626
- * Called from index.ts after all components are initialized.
4627
- */
4628
- setDependencies(deps) {
4629
- this.policy = deps.policy;
4630
- this.baseline = deps.baseline;
4631
- this.auditLog = deps.auditLog;
4324
+
4325
+ .activity-tier {
4326
+ display: inline-flex;
4327
+ align-items: center;
4328
+ justify-content: center;
4329
+ width: 24px;
4330
+ height: 16px;
4331
+ font-size: 10px;
4332
+ font-weight: 700;
4333
+ border-radius: 3px;
4334
+ text-transform: uppercase;
4335
+ flex: 0 0 auto;
4632
4336
  }
4633
- /**
4634
- * Start the HTTP(S) server for the dashboard.
4635
- */
4636
- async start() {
4637
- return new Promise((resolve, reject) => {
4638
- const handler = (req, res) => this.handleRequest(req, res);
4639
- if (this.useTLS && this.config.tls) {
4640
- const tlsOpts = {
4641
- cert: readFileSync(this.config.tls.cert_path),
4642
- key: readFileSync(this.config.tls.key_path)
4643
- };
4644
- this.httpServer = createServer$1(tlsOpts, handler);
4645
- } else {
4646
- this.httpServer = createServer$2(handler);
4647
- }
4648
- const protocol = this.useTLS ? "https" : "http";
4649
- const baseUrl = `${protocol}://${this.config.host}:${this.config.port}`;
4650
- this.httpServer.listen(this.config.port, this.config.host, () => {
4651
- if (this.authToken) {
4652
- const hint = this.authToken.slice(0, 4) + "..." + this.authToken.slice(-4);
4653
- process.stderr.write(
4654
- `
4655
- Sanctuary Principal Dashboard: ${baseUrl}
4656
- `
4657
- );
4658
- process.stderr.write(
4659
- ` Auth required (token: ${hint}). Use Authorization: Bearer <TOKEN> header.
4660
4337
 
4661
- `
4662
- );
4663
- } else {
4664
- process.stderr.write(
4665
- `
4666
- Sanctuary Principal Dashboard: ${baseUrl}
4338
+ .activity-tier.t1 {
4339
+ background: rgba(248, 81, 73, 0.2);
4340
+ color: var(--red);
4341
+ }
4667
4342
 
4668
- `
4669
- );
4670
- }
4671
- resolve();
4672
- });
4673
- this.httpServer.on("error", reject);
4674
- });
4343
+ .activity-tier.t2 {
4344
+ background: rgba(210, 153, 34, 0.2);
4345
+ color: var(--amber);
4675
4346
  }
4676
- /**
4677
- * Stop the HTTP server and clean up.
4678
- */
4679
- async stop() {
4680
- for (const [, pending] of this.pending) {
4681
- clearTimeout(pending.timer);
4682
- pending.resolve({
4683
- decision: "deny",
4347
+
4348
+ .activity-tier.t3 {
4349
+ background: rgba(63, 185, 80, 0.2);
4350
+ color: var(--green);
4351
+ }
4352
+
4353
+ .activity-tool {
4354
+ color: var(--text-primary);
4355
+ font-weight: 600;
4356
+ }
4357
+
4358
+ .activity-outcome {
4359
+ color: var(--green);
4360
+ }
4361
+
4362
+ .activity-outcome.denied {
4363
+ color: var(--red);
4364
+ }
4365
+
4366
+ .activity-detail {
4367
+ font-size: 12px;
4368
+ color: var(--text-secondary);
4369
+ margin-left: 0;
4370
+ }
4371
+
4372
+ .activity-item.expanded .activity-detail {
4373
+ display: block;
4374
+ margin-top: 8px;
4375
+ padding: 10px;
4376
+ background: rgba(88, 166, 255, 0.08);
4377
+ border-left: 2px solid var(--blue);
4378
+ border-radius: 4px;
4379
+ }
4380
+
4381
+ .activity-empty {
4382
+ display: flex;
4383
+ flex-direction: column;
4384
+ align-items: center;
4385
+ justify-content: center;
4386
+ height: 100%;
4387
+ color: var(--text-secondary);
4388
+ }
4389
+
4390
+ .activity-empty-icon {
4391
+ font-size: 32px;
4392
+ margin-bottom: 12px;
4393
+ }
4394
+
4395
+ .activity-empty-text {
4396
+ font-size: 14px;
4397
+ }
4398
+
4399
+ /* \u2500\u2500 Protection Status Sidebar (40%) \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 */
4400
+
4401
+ .protection-sidebar {
4402
+ flex: 2;
4403
+ display: flex;
4404
+ flex-direction: column;
4405
+ background: rgba(22, 27, 34, 0.5);
4406
+ overflow: hidden;
4407
+ }
4408
+
4409
+ .sidebar-header {
4410
+ padding: 16px 20px;
4411
+ border-bottom: 1px solid var(--border);
4412
+ font-size: 12px;
4413
+ font-weight: 600;
4414
+ text-transform: uppercase;
4415
+ letter-spacing: 0.5px;
4416
+ color: var(--text-secondary);
4417
+ display: flex;
4418
+ align-items: center;
4419
+ gap: 8px;
4420
+ }
4421
+
4422
+ .sidebar-content {
4423
+ flex: 1;
4424
+ overflow-y: auto;
4425
+ padding: 16px 16px;
4426
+ display: grid;
4427
+ grid-template-columns: 1fr 1fr;
4428
+ gap: 12px;
4429
+ }
4430
+
4431
+ .protection-card {
4432
+ background: var(--surface);
4433
+ border: 1px solid var(--border);
4434
+ border-radius: var(--radius);
4435
+ padding: 14px;
4436
+ display: flex;
4437
+ flex-direction: column;
4438
+ gap: 8px;
4439
+ }
4440
+
4441
+ .protection-card-icon {
4442
+ font-size: 14px;
4443
+ }
4444
+
4445
+ .protection-card-label {
4446
+ font-size: 11px;
4447
+ font-weight: 600;
4448
+ text-transform: uppercase;
4449
+ letter-spacing: 0.5px;
4450
+ color: var(--text-secondary);
4451
+ }
4452
+
4453
+ .protection-card-status {
4454
+ display: flex;
4455
+ align-items: center;
4456
+ gap: 6px;
4457
+ font-size: 12px;
4458
+ font-weight: 600;
4459
+ }
4460
+
4461
+ .protection-card-status.active {
4462
+ color: var(--green);
4463
+ }
4464
+
4465
+ .protection-card-status.inactive {
4466
+ color: var(--text-secondary);
4467
+ }
4468
+
4469
+ .protection-card-stat {
4470
+ font-size: 11px;
4471
+ color: var(--text-secondary);
4472
+ font-family: var(--mono);
4473
+ margin-top: 4px;
4474
+ }
4475
+
4476
+ /* \u2500\u2500 Pending Approvals Overlay \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 */
4477
+
4478
+ .pending-overlay {
4479
+ position: fixed;
4480
+ top: 56px;
4481
+ right: 0;
4482
+ bottom: 0;
4483
+ width: 0;
4484
+ background: var(--surface);
4485
+ border-left: 1px solid var(--border);
4486
+ z-index: 999;
4487
+ overflow-y: auto;
4488
+ transition: width 0.3s ease-out;
4489
+ display: flex;
4490
+ flex-direction: column;
4491
+ }
4492
+
4493
+ .pending-overlay.active {
4494
+ width: 380px;
4495
+ }
4496
+
4497
+ @media (max-width: 1400px) {
4498
+ .pending-overlay.active {
4499
+ width: 100%;
4500
+ right: auto;
4501
+ left: 0;
4502
+ }
4503
+ }
4504
+
4505
+ .pending-overlay-header {
4506
+ padding: 16px 20px;
4507
+ border-bottom: 1px solid var(--border);
4508
+ display: flex;
4509
+ align-items: center;
4510
+ justify-content: space-between;
4511
+ flex: 0 0 auto;
4512
+ }
4513
+
4514
+ .pending-overlay-title {
4515
+ font-size: 13px;
4516
+ font-weight: 600;
4517
+ text-transform: uppercase;
4518
+ letter-spacing: 0.5px;
4519
+ color: var(--text-primary);
4520
+ }
4521
+
4522
+ .pending-overlay-close {
4523
+ background: none;
4524
+ border: none;
4525
+ color: var(--text-secondary);
4526
+ cursor: pointer;
4527
+ font-size: 18px;
4528
+ padding: 0;
4529
+ display: flex;
4530
+ align-items: center;
4531
+ justify-content: center;
4532
+ }
4533
+
4534
+ .pending-overlay-close:hover {
4535
+ color: var(--text-primary);
4536
+ }
4537
+
4538
+ .pending-list {
4539
+ flex: 1;
4540
+ overflow-y: auto;
4541
+ }
4542
+
4543
+ .pending-item {
4544
+ padding: 16px 20px;
4545
+ border-bottom: 1px solid rgba(48, 54, 61, 0.5);
4546
+ display: flex;
4547
+ flex-direction: column;
4548
+ gap: 10px;
4549
+ }
4550
+
4551
+ .pending-item-header {
4552
+ display: flex;
4553
+ align-items: center;
4554
+ gap: 8px;
4555
+ }
4556
+
4557
+ .pending-item-op {
4558
+ font-family: var(--mono);
4559
+ font-size: 12px;
4560
+ font-weight: 600;
4561
+ color: var(--text-primary);
4562
+ flex: 1;
4563
+ }
4564
+
4565
+ .pending-item-tier {
4566
+ display: inline-flex;
4567
+ align-items: center;
4568
+ justify-content: center;
4569
+ width: 28px;
4570
+ height: 20px;
4571
+ font-size: 9px;
4572
+ font-weight: 700;
4573
+ border-radius: 3px;
4574
+ text-transform: uppercase;
4575
+ color: white;
4576
+ }
4577
+
4578
+ .pending-item-tier.tier1 {
4579
+ background: var(--red);
4580
+ }
4581
+
4582
+ .pending-item-tier.tier2 {
4583
+ background: var(--amber);
4584
+ }
4585
+
4586
+ .pending-item-reason {
4587
+ font-size: 12px;
4588
+ color: var(--text-secondary);
4589
+ }
4590
+
4591
+ .pending-item-timer {
4592
+ display: flex;
4593
+ align-items: center;
4594
+ gap: 6px;
4595
+ font-size: 11px;
4596
+ font-family: var(--mono);
4597
+ color: var(--text-secondary);
4598
+ }
4599
+
4600
+ .pending-item-timer-bar {
4601
+ flex: 1;
4602
+ height: 4px;
4603
+ background: rgba(48, 54, 61, 0.8);
4604
+ border-radius: 2px;
4605
+ overflow: hidden;
4606
+ }
4607
+
4608
+ .pending-item-timer-fill {
4609
+ height: 100%;
4610
+ background: var(--blue);
4611
+ transition: width 0.1s linear;
4612
+ }
4613
+
4614
+ .pending-item-timer.urgent .pending-item-timer-fill {
4615
+ background: var(--red);
4616
+ }
4617
+
4618
+ .pending-item-actions {
4619
+ display: flex;
4620
+ gap: 8px;
4621
+ }
4622
+
4623
+ .btn {
4624
+ flex: 1;
4625
+ padding: 8px 12px;
4626
+ border: none;
4627
+ border-radius: var(--radius);
4628
+ font-size: 12px;
4629
+ font-weight: 600;
4630
+ cursor: pointer;
4631
+ transition: all 0.15s;
4632
+ font-family: var(--sans);
4633
+ }
4634
+
4635
+ .btn-approve {
4636
+ background: var(--green);
4637
+ color: var(--bg);
4638
+ }
4639
+
4640
+ .btn-approve:hover {
4641
+ background: #4ecf5e;
4642
+ }
4643
+
4644
+ .btn-deny {
4645
+ background: var(--red);
4646
+ color: white;
4647
+ }
4648
+
4649
+ .btn-deny:hover {
4650
+ background: #f9605e;
4651
+ }
4652
+
4653
+ /* \u2500\u2500 Threat Panel (collapsible footer) \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 */
4654
+
4655
+ .threat-panel {
4656
+ position: fixed;
4657
+ bottom: 0;
4658
+ left: 0;
4659
+ right: 0;
4660
+ background: var(--surface);
4661
+ border-top: 1px solid var(--border);
4662
+ max-height: 240px;
4663
+ z-index: 500;
4664
+ display: flex;
4665
+ flex-direction: column;
4666
+ transition: max-height 0.3s ease-out;
4667
+ }
4668
+
4669
+ .threat-panel.collapsed {
4670
+ max-height: 40px;
4671
+ }
4672
+
4673
+ .threat-header {
4674
+ padding: 12px 20px;
4675
+ cursor: pointer;
4676
+ display: flex;
4677
+ align-items: center;
4678
+ gap: 8px;
4679
+ font-size: 12px;
4680
+ font-weight: 600;
4681
+ text-transform: uppercase;
4682
+ letter-spacing: 0.5px;
4683
+ color: var(--text-secondary);
4684
+ flex: 0 0 auto;
4685
+ }
4686
+
4687
+ .threat-header:hover {
4688
+ background: rgba(88, 166, 255, 0.05);
4689
+ }
4690
+
4691
+ .threat-icon {
4692
+ font-size: 14px;
4693
+ }
4694
+
4695
+ .threat-content {
4696
+ flex: 1;
4697
+ overflow-y: auto;
4698
+ padding: 0 20px 12px;
4699
+ display: flex;
4700
+ flex-direction: column;
4701
+ gap: 10px;
4702
+ }
4703
+
4704
+ .threat-item {
4705
+ padding: 8px 10px;
4706
+ background: rgba(248, 81, 73, 0.1);
4707
+ border-left: 2px solid var(--red);
4708
+ border-radius: 4px;
4709
+ font-size: 11px;
4710
+ color: var(--text-secondary);
4711
+ }
4712
+
4713
+ .threat-item-type {
4714
+ font-weight: 600;
4715
+ color: var(--red);
4716
+ font-family: var(--mono);
4717
+ }
4718
+
4719
+ .threat-empty {
4720
+ text-align: center;
4721
+ padding: 20px 10px;
4722
+ color: var(--text-secondary);
4723
+ font-size: 12px;
4724
+ }
4725
+
4726
+ /* \u2500\u2500 Scrollbars \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 */
4727
+
4728
+ ::-webkit-scrollbar {
4729
+ width: 6px;
4730
+ }
4731
+
4732
+ ::-webkit-scrollbar-track {
4733
+ background: transparent;
4734
+ }
4735
+
4736
+ ::-webkit-scrollbar-thumb {
4737
+ background: var(--border);
4738
+ border-radius: 3px;
4739
+ }
4740
+
4741
+ ::-webkit-scrollbar-thumb:hover {
4742
+ background: rgba(88, 166, 255, 0.3);
4743
+ }
4744
+
4745
+ /* \u2500\u2500 Responsive \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 */
4746
+
4747
+ @media (max-width: 1200px) {
4748
+ .protection-sidebar {
4749
+ display: none;
4750
+ }
4751
+
4752
+ .activity-feed {
4753
+ border-right: none;
4754
+ }
4755
+ }
4756
+
4757
+ @media (max-width: 768px) {
4758
+ .status-bar {
4759
+ padding: 0 12px;
4760
+ gap: 12px;
4761
+ height: 48px;
4762
+ }
4763
+
4764
+ .sanctuary-logo {
4765
+ font-size: 14px;
4766
+ }
4767
+
4768
+ .status-bar-center {
4769
+ display: none;
4770
+ }
4771
+
4772
+ .main-container {
4773
+ margin-top: 48px;
4774
+ }
4775
+
4776
+ .activity-item {
4777
+ padding: 10px 12px;
4778
+ }
4779
+
4780
+ .pending-overlay.active {
4781
+ width: 100%;
4782
+ }
4783
+
4784
+ .threat-panel {
4785
+ max-height: 200px;
4786
+ }
4787
+ }
4788
+ </style>
4789
+ </head>
4790
+ <body>
4791
+
4792
+ <!-- Status Bar (fixed, top) -->
4793
+ <div class="status-bar">
4794
+ <div class="status-bar-left">
4795
+ <div class="sanctuary-logo"><span>\u25C6</span> SANCTUARY</div>
4796
+ <div class="version">v${options.serverVersion}</div>
4797
+ </div>
4798
+ <div class="status-bar-center">
4799
+ <div class="sovereignty-badge">
4800
+ <div class="sovereignty-score" id="sovereigntyScore">85</div>
4801
+ <span>Sovereignty Health</span>
4802
+ </div>
4803
+ </div>
4804
+ <div class="status-bar-right">
4805
+ <div class="protections-indicator">
4806
+ <span class="count" id="activeProtections">6</span>/6 protections
4807
+ </div>
4808
+ <div class="uptime">
4809
+ <span id="uptimeText">\u2014</span>
4810
+ </div>
4811
+ <div class="status-dot" id="statusDot"></div>
4812
+ <div class="pending-badge hidden" id="pendingBadge">0</div>
4813
+ </div>
4814
+ </div>
4815
+
4816
+ <!-- Main Layout -->
4817
+ <div class="main-container">
4818
+ <!-- Activity Feed -->
4819
+ <div class="activity-feed">
4820
+ <div class="feed-header">
4821
+ <div class="feed-header-dot"></div>
4822
+ Live Activity
4823
+ </div>
4824
+ <div class="activity-list" id="activityList">
4825
+ <div class="activity-empty">
4826
+ <div class="activity-empty-icon">\u2192</div>
4827
+ <div class="activity-empty-text">Waiting for activity...</div>
4828
+ </div>
4829
+ </div>
4830
+ </div>
4831
+
4832
+ <!-- Protection Status Sidebar -->
4833
+ <div class="protection-sidebar" id="protectionSidebar">
4834
+ <div class="sidebar-header">
4835
+ <span>\u25C6</span> Protection Status
4836
+ </div>
4837
+ <div class="sidebar-content">
4838
+ <div class="protection-card">
4839
+ <div class="protection-card-icon">\u{1F510}</div>
4840
+ <div class="protection-card-label">Encryption</div>
4841
+ <div class="protection-card-status active" id="encryptionStatus">\u2713 Active</div>
4842
+ <div class="protection-card-stat" id="encryptionStat">Ed25519</div>
4843
+ </div>
4844
+
4845
+ <div class="protection-card">
4846
+ <div class="protection-card-icon">\u2713</div>
4847
+ <div class="protection-card-label">Approval Gate</div>
4848
+ <div class="protection-card-status active" id="approvalStatus">\u2713 Active</div>
4849
+ <div class="protection-card-stat" id="approvalStat">T1: 2 | T2: 3</div>
4850
+ </div>
4851
+
4852
+ <div class="protection-card">
4853
+ <div class="protection-card-icon">\u{1F3AF}</div>
4854
+ <div class="protection-card-label">Context Gating</div>
4855
+ <div class="protection-card-status active" id="contextStatus">\u2713 Active</div>
4856
+ <div class="protection-card-stat" id="contextStat">12 filtered</div>
4857
+ </div>
4858
+
4859
+ <div class="protection-card">
4860
+ <div class="protection-card-icon">\u26A0</div>
4861
+ <div class="protection-card-label">Injection Detection</div>
4862
+ <div class="protection-card-status active" id="injectionStatus">\u2713 Active</div>
4863
+ <div class="protection-card-stat" id="injectionStat">3 flags today</div>
4864
+ </div>
4865
+
4866
+ <div class="protection-card">
4867
+ <div class="protection-card-icon">\u{1F4CA}</div>
4868
+ <div class="protection-card-label">Behavioral Baseline</div>
4869
+ <div class="protection-card-status active" id="baselineStatus">\u2713 Active</div>
4870
+ <div class="protection-card-stat" id="baselineStat">0 anomalies</div>
4871
+ </div>
4872
+
4873
+ <div class="protection-card">
4874
+ <div class="protection-card-icon">\u{1F4CB}</div>
4875
+ <div class="protection-card-label">Audit Trail</div>
4876
+ <div class="protection-card-status active" id="auditStatus">\u2713 Active</div>
4877
+ <div class="protection-card-stat" id="auditStat">284 entries</div>
4878
+ </div>
4879
+ </div>
4880
+ </div>
4881
+ </div>
4882
+
4883
+ <!-- Pending Approvals Overlay -->
4884
+ <div class="pending-overlay" id="pendingOverlay">
4885
+ <div class="pending-overlay-header">
4886
+ <div class="pending-overlay-title">Pending Approvals</div>
4887
+ <button class="pending-overlay-close" onclick="closePendingOverlay()">\xD7</button>
4888
+ </div>
4889
+ <div class="pending-list" id="pendingList"></div>
4890
+ </div>
4891
+
4892
+ <!-- Threat Panel (collapsible footer) -->
4893
+ <div class="threat-panel collapsed" id="threatPanel">
4894
+ <div class="threat-header" onclick="toggleThreatPanel()">
4895
+ <span class="threat-icon">\u26A0</span>
4896
+ Recent Threats
4897
+ <span id="threatCount" style="margin-left: auto; color: var(--red); font-weight: 700;">0</span>
4898
+ </div>
4899
+ <div class="threat-content" id="threatContent">
4900
+ <div class="threat-empty">No threats detected</div>
4901
+ </div>
4902
+ </div>
4903
+
4904
+ <script>
4905
+ (function() {
4906
+ 'use strict';
4907
+
4908
+ // \u2500\u2500 Configuration \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
4909
+
4910
+ const TIMEOUT_SECONDS = ${options.timeoutSeconds};
4911
+ const AUTH_TOKEN = ${options.authToken ? JSON.stringify(options.authToken) : "null"};
4912
+ const MAX_ACTIVITY_ITEMS = 100;
4913
+ const MAX_THREAT_ITEMS = 20;
4914
+
4915
+ // \u2500\u2500 State \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\u2500\u2500\u2500\u2500
4916
+
4917
+ let SESSION_ID = null;
4918
+ let evtSource = null;
4919
+ let startTime = Date.now();
4920
+ let activityCount = 0;
4921
+ let threatCount = 0;
4922
+ const pendingRequests = new Map();
4923
+ const activityItems = [];
4924
+ const threatItems = [];
4925
+ let sovereigntyScore = 85;
4926
+
4927
+ // \u2500\u2500 Auth Helpers (SEC-012) \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
4928
+
4929
+ function authHeaders() {
4930
+ const h = { 'Content-Type': 'application/json' };
4931
+ if (AUTH_TOKEN) h['Authorization'] = 'Bearer ' + AUTH_TOKEN;
4932
+ return h;
4933
+ }
4934
+
4935
+ function sessionQuery(url) {
4936
+ if (!SESSION_ID) return url;
4937
+ const sep = url.includes('?') ? '&' : '?';
4938
+ return url + sep + 'session=' + SESSION_ID;
4939
+ }
4940
+
4941
+ async function exchangeSession() {
4942
+ if (!AUTH_TOKEN) return;
4943
+ try {
4944
+ const resp = await fetch('/auth/session', { method: 'POST', headers: authHeaders() });
4945
+ if (resp.ok) {
4946
+ const data = await resp.json();
4947
+ SESSION_ID = data.session_id;
4948
+ const refreshMs = (data.expires_in_seconds || 300) * 800;
4949
+ setTimeout(() => { exchangeSession(); reconnectSSE(); }, refreshMs);
4950
+ }
4951
+ } catch (e) {
4952
+ // Retry on next connect
4953
+ }
4954
+ }
4955
+
4956
+ // \u2500\u2500 UI Utilities \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
4957
+
4958
+ function esc(s) {
4959
+ const d = document.createElement('div');
4960
+ d.textContent = String(s || '');
4961
+ return d.innerHTML;
4962
+ }
4963
+
4964
+ function closePendingOverlay() {
4965
+ document.getElementById('pendingOverlay').classList.remove('active');
4966
+ }
4967
+
4968
+ function toggleThreatPanel() {
4969
+ document.getElementById('threatPanel').classList.toggle('collapsed');
4970
+ }
4971
+
4972
+ function updateUptime() {
4973
+ const elapsed = Math.floor((Date.now() - startTime) / 1000);
4974
+ const hours = Math.floor(elapsed / 3600);
4975
+ const mins = Math.floor((elapsed % 3600) / 60);
4976
+ const secs = elapsed % 60;
4977
+ let uptimeStr = '';
4978
+ if (hours > 0) uptimeStr += hours + 'h ';
4979
+ if (mins > 0) uptimeStr += mins + 'm ';
4980
+ uptimeStr += secs + 's';
4981
+ document.getElementById('uptimeText').textContent = uptimeStr;
4982
+ }
4983
+
4984
+ // \u2500\u2500 Sovereignty Score \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
4985
+
4986
+ function updateSovereigntyScore(score) {
4987
+ sovereigntyScore = Math.min(100, Math.max(0, score || 85));
4988
+ const badge = document.getElementById('sovereigntyScore');
4989
+ badge.textContent = sovereigntyScore;
4990
+ badge.className = 'sovereignty-score';
4991
+ if (sovereigntyScore >= 80) {
4992
+ badge.classList.add('high');
4993
+ } else if (sovereigntyScore >= 50) {
4994
+ badge.classList.add('medium');
4995
+ } else {
4996
+ badge.classList.add('low');
4997
+ }
4998
+ }
4999
+
5000
+ // \u2500\u2500 Activity Feed \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
5001
+
5002
+ function addActivityItem(data) {
5003
+ const {
5004
+ timestamp,
5005
+ tier,
5006
+ tool,
5007
+ outcome,
5008
+ detail,
5009
+ hasInjection,
5010
+ isContextGated
5011
+ } = data;
5012
+
5013
+ const item = {
5014
+ id: 'activity-' + activityCount++,
5015
+ timestamp: timestamp || new Date().toISOString(),
5016
+ tier: tier || 1,
5017
+ tool: tool || 'unknown_tool',
5018
+ outcome: outcome || 'executed',
5019
+ detail: detail || '',
5020
+ hasInjection: !!hasInjection,
5021
+ isContextGated: !!isContextGated
5022
+ };
5023
+
5024
+ activityItems.unshift(item);
5025
+ if (activityItems.length > MAX_ACTIVITY_ITEMS) {
5026
+ activityItems.pop();
5027
+ }
5028
+
5029
+ renderActivityFeed();
5030
+ }
5031
+
5032
+ function renderActivityFeed() {
5033
+ const list = document.getElementById('activityList');
5034
+
5035
+ if (activityItems.length === 0) {
5036
+ list.innerHTML = '<div class="activity-empty"><div class="activity-empty-icon">\u2192</div><div class="activity-empty-text">Waiting for activity...</div></div>';
5037
+ return;
5038
+ }
5039
+
5040
+ list.innerHTML = '';
5041
+ for (const item of activityItems) {
5042
+ const tr = document.createElement('div');
5043
+ tr.className = 'activity-item';
5044
+ tr.id = item.id;
5045
+
5046
+ const time = new Date(item.timestamp);
5047
+ const timeStr = time.toLocaleTimeString();
5048
+
5049
+ const tierClass = 't' + item.tier;
5050
+ const outcomeClass = item.outcome === 'denied' ? 'outcome denied' : 'outcome';
5051
+
5052
+ let icon = '\u25CF';
5053
+ if (item.isContextGated) icon = '\u{1F3AF}';
5054
+ else if (item.hasInjection) icon = '\u26A0';
5055
+ else if (item.outcome === 'denied') icon = '\u2717';
5056
+ else icon = '\u2713';
5057
+
5058
+ tr.innerHTML =
5059
+ '<div class="activity-item-icon">' + esc(icon) + '</div>' +
5060
+ '<div class="activity-item-content">' +
5061
+ '<div class="activity-time">' + esc(timeStr) + '</div>' +
5062
+ '<div class="activity-main">' +
5063
+ '<span class="activity-tier ' + tierClass + '">T' + item.tier + '</span>' +
5064
+ '<span class="activity-tool">' + esc(item.tool) + '</span>' +
5065
+ '<span class="activity-outcome ' + (outcomeClass === 'outcome denied' ? 'denied' : '') + '">' + (item.outcome === 'denied' ? '\u2717 denied' : '\u2713 allowed') + '</span>' +
5066
+ '</div>' +
5067
+ '<div class="activity-detail">' + esc(item.detail) + '</div>' +
5068
+ '</div>' +
5069
+ '';
5070
+
5071
+ tr.addEventListener('click', () => {
5072
+ tr.classList.toggle('expanded');
5073
+ });
5074
+
5075
+ list.appendChild(tr);
5076
+ }
5077
+ }
5078
+
5079
+ // \u2500\u2500 Pending Approvals \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
5080
+
5081
+ function addPendingRequest(data) {
5082
+ const {
5083
+ request_id,
5084
+ operation,
5085
+ tier,
5086
+ reason,
5087
+ context,
5088
+ timestamp
5089
+ } = data;
5090
+
5091
+ const pending = {
5092
+ id: request_id,
5093
+ operation: operation || 'unknown',
5094
+ tier: tier || 1,
5095
+ reason: reason || '',
5096
+ context: context || {},
5097
+ timestamp: timestamp || new Date().toISOString(),
5098
+ remaining: TIMEOUT_SECONDS
5099
+ };
5100
+
5101
+ pendingRequests.set(request_id, pending);
5102
+ updatePendingUI();
5103
+ }
5104
+
5105
+ function removePendingRequest(id) {
5106
+ pendingRequests.delete(id);
5107
+ updatePendingUI();
5108
+ }
5109
+
5110
+ function updatePendingUI() {
5111
+ const count = pendingRequests.size;
5112
+ const badge = document.getElementById('pendingBadge');
5113
+
5114
+ if (count > 0) {
5115
+ badge.classList.remove('hidden');
5116
+ badge.textContent = count;
5117
+ document.getElementById('pendingOverlay').classList.add('active');
5118
+ } else {
5119
+ badge.classList.add('hidden');
5120
+ document.getElementById('pendingOverlay').classList.remove('active');
5121
+ }
5122
+
5123
+ renderPendingList();
5124
+ }
5125
+
5126
+ function renderPendingList() {
5127
+ const list = document.getElementById('pendingList');
5128
+ list.innerHTML = '';
5129
+
5130
+ for (const [id, req] of pendingRequests) {
5131
+ const item = document.createElement('div');
5132
+ item.className = 'pending-item';
5133
+
5134
+ const tier = req.tier || 1;
5135
+ const tierClass = 'tier' + tier;
5136
+ const pct = Math.max(0, Math.min(100, (req.remaining / TIMEOUT_SECONDS) * 100));
5137
+ const isUrgent = req.remaining <= 30;
5138
+
5139
+ item.innerHTML =
5140
+ '<div class="pending-item-header">' +
5141
+ '<div class="pending-item-op">' + esc(req.operation) + '</div>' +
5142
+ '<div class="pending-item-tier ' + tierClass + '">T' + tier + '</div>' +
5143
+ '</div>' +
5144
+ '<div class="pending-item-reason">' + esc(req.reason) + '</div>' +
5145
+ '<div class="pending-item-timer ' + (isUrgent ? 'urgent' : '') + '">' +
5146
+ '<div class="pending-item-timer-bar">' +
5147
+ '<div class="pending-item-timer-fill" style="width: ' + pct + '%"></div>' +
5148
+ '</div>' +
5149
+ '<span id="timer-' + id + '">' + req.remaining + 's</span>' +
5150
+ '</div>' +
5151
+ '<div class="pending-item-actions">' +
5152
+ '<button class="btn btn-approve" onclick="handleApprove('' + id + '')">Approve</button>' +
5153
+ '<button class="btn btn-deny" onclick="handleDeny('' + id + '')">Deny</button>' +
5154
+ '</div>' +
5155
+ '';
5156
+
5157
+ list.appendChild(item);
5158
+ }
5159
+ }
5160
+
5161
+ window.handleApprove = function(id) {
5162
+ fetch('/api/approve/' + id, { method: 'POST', headers: authHeaders() }).then(() => {
5163
+ removePendingRequest(id);
5164
+ }).catch(() => {});
5165
+ };
5166
+
5167
+ window.handleDeny = function(id) {
5168
+ fetch('/api/deny/' + id, { method: 'POST', headers: authHeaders() }).then(() => {
5169
+ removePendingRequest(id);
5170
+ }).catch(() => {});
5171
+ };
5172
+
5173
+ // \u2500\u2500 Threats \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\u2500\u2500
5174
+
5175
+ function addThreat(data) {
5176
+ const {
5177
+ timestamp,
5178
+ severity,
5179
+ type,
5180
+ details
5181
+ } = data;
5182
+
5183
+ const threat = {
5184
+ id: 'threat-' + threatCount++,
5185
+ timestamp: timestamp || new Date().toISOString(),
5186
+ severity: severity || 'medium',
5187
+ type: type || 'unknown',
5188
+ details: details || ''
5189
+ };
5190
+
5191
+ threatItems.unshift(threat);
5192
+ if (threatItems.length > MAX_THREAT_ITEMS) {
5193
+ threatItems.pop();
5194
+ }
5195
+
5196
+ if (threatCount > 0) {
5197
+ document.getElementById('threatPanel').classList.remove('collapsed');
5198
+ }
5199
+
5200
+ renderThreats();
5201
+ }
5202
+
5203
+ function renderThreats() {
5204
+ const content = document.getElementById('threatContent');
5205
+ const badge = document.getElementById('threatCount');
5206
+
5207
+ if (threatItems.length === 0) {
5208
+ content.innerHTML = '<div class="threat-empty">No threats detected</div>';
5209
+ badge.textContent = '0';
5210
+ return;
5211
+ }
5212
+
5213
+ badge.textContent = threatItems.length;
5214
+ content.innerHTML = '';
5215
+
5216
+ for (const threat of threatItems) {
5217
+ const div = document.createElement('div');
5218
+ div.className = 'threat-item';
5219
+ const time = new Date(threat.timestamp).toLocaleTimeString();
5220
+ div.innerHTML =
5221
+ '<div style="margin-bottom: 3px;">' +
5222
+ '<span class="threat-item-type">' + esc(threat.type) + '</span>' +
5223
+ '<span style="font-size: 10px; color: var(--text-secondary); margin-left: 6px;">' + esc(time) + '</span>' +
5224
+ '</div>' +
5225
+ '<div>' + esc(threat.details) + '</div>' +
5226
+ '';
5227
+ content.appendChild(div);
5228
+ }
5229
+ }
5230
+
5231
+ // \u2500\u2500 SSE Connection \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
5232
+
5233
+ function reconnectSSE() {
5234
+ if (evtSource) evtSource.close();
5235
+ connect();
5236
+ }
5237
+
5238
+ function connect() {
5239
+ evtSource = new EventSource(sessionQuery('/events'));
5240
+
5241
+ evtSource.onopen = () => {
5242
+ document.getElementById('statusDot').classList.remove('disconnected');
5243
+ };
5244
+
5245
+ evtSource.onerror = () => {
5246
+ document.getElementById('statusDot').classList.add('disconnected');
5247
+ };
5248
+
5249
+ evtSource.addEventListener('init', (e) => {
5250
+ const data = JSON.parse(e.data);
5251
+ if (data.baseline) {
5252
+ updateBaseline(data.baseline);
5253
+ }
5254
+ if (data.policy) {
5255
+ updatePolicy(data.policy);
5256
+ }
5257
+ if (data.pending) {
5258
+ data.pending.forEach(addPendingRequest);
5259
+ }
5260
+ });
5261
+
5262
+ evtSource.addEventListener('pending-request', (e) => {
5263
+ const data = JSON.parse(e.data);
5264
+ addPendingRequest(data);
5265
+ });
5266
+
5267
+ evtSource.addEventListener('request-resolved', (e) => {
5268
+ const data = JSON.parse(e.data);
5269
+ removePendingRequest(data.request_id);
5270
+ });
5271
+
5272
+ evtSource.addEventListener('tool-call', (e) => {
5273
+ const data = JSON.parse(e.data);
5274
+ addActivityItem({
5275
+ timestamp: data.timestamp,
5276
+ tier: data.tier || 1,
5277
+ tool: data.tool || 'unknown',
5278
+ outcome: data.outcome || 'executed',
5279
+ detail: data.detail || ''
5280
+ });
5281
+ });
5282
+
5283
+ evtSource.addEventListener('context-gate-decision', (e) => {
5284
+ const data = JSON.parse(e.data);
5285
+ addActivityItem({
5286
+ timestamp: data.timestamp,
5287
+ tier: data.tier || 1,
5288
+ tool: data.tool || 'unknown',
5289
+ outcome: data.outcome || 'gated',
5290
+ detail: data.fields_filtered ? 'Filtered ' + data.fields_filtered + ' fields' : data.reason || '',
5291
+ isContextGated: true
5292
+ });
5293
+ });
5294
+
5295
+ evtSource.addEventListener('injection-alert', (e) => {
5296
+ const data = JSON.parse(e.data);
5297
+ addActivityItem({
5298
+ timestamp: data.timestamp,
5299
+ tier: data.tier || 2,
5300
+ tool: data.tool || 'unknown',
5301
+ outcome: data.allowed ? 'allowed' : 'denied',
5302
+ detail: data.signal || 'Injection detected',
5303
+ hasInjection: true
5304
+ });
5305
+ addThreat({
5306
+ timestamp: data.timestamp,
5307
+ severity: data.severity || 'medium',
5308
+ type: 'Injection Alert',
5309
+ details: data.signal || 'Suspicious pattern detected'
5310
+ });
5311
+ });
5312
+
5313
+ evtSource.addEventListener('protection-status', (e) => {
5314
+ const data = JSON.parse(e.data);
5315
+ updateProtectionStatus(data);
5316
+ });
5317
+
5318
+ evtSource.addEventListener('audit-entry', (e) => {
5319
+ const data = JSON.parse(e.data);
5320
+ // Audit entries don't show in activity by default, but we could add them
5321
+ });
5322
+
5323
+ evtSource.addEventListener('baseline-update', (e) => {
5324
+ const data = JSON.parse(e.data);
5325
+ updateBaseline(data);
5326
+ });
5327
+ }
5328
+
5329
+ function updateBaseline(baseline) {
5330
+ if (!baseline) return;
5331
+ // Update baseline-derived stats if needed
5332
+ }
5333
+
5334
+ function updatePolicy(policy) {
5335
+ if (!policy) return;
5336
+ // Update policy-derived stats
5337
+ if (policy.approval_channel) {
5338
+ // Policy info updated
5339
+ }
5340
+ }
5341
+
5342
+ function updateProtectionStatus(status) {
5343
+ if (status.sovereignty_score !== undefined) {
5344
+ updateSovereigntyScore(status.sovereignty_score);
5345
+ }
5346
+ if (status.active_protections !== undefined) {
5347
+ document.getElementById('activeProtections').textContent = status.active_protections;
5348
+ }
5349
+ // Update individual protection cards
5350
+ if (status.encryption !== undefined) {
5351
+ const el = document.getElementById('encryptionStatus');
5352
+ el.className = 'protection-card-status ' + (status.encryption ? 'active' : 'inactive');
5353
+ el.textContent = status.encryption ? '\u2713 Active' : '\u2717 Inactive';
5354
+ }
5355
+ if (status.approval_gate !== undefined) {
5356
+ const el = document.getElementById('approvalStatus');
5357
+ el.className = 'protection-card-status ' + (status.approval_gate ? 'active' : 'inactive');
5358
+ el.textContent = status.approval_gate ? '\u2713 Active' : '\u2717 Inactive';
5359
+ }
5360
+ if (status.context_gating !== undefined) {
5361
+ const el = document.getElementById('contextStatus');
5362
+ el.className = 'protection-card-status ' + (status.context_gating ? 'active' : 'inactive');
5363
+ el.textContent = status.context_gating ? '\u2713 Active' : '\u2717 Inactive';
5364
+ }
5365
+ if (status.injection_detection !== undefined) {
5366
+ const el = document.getElementById('injectionStatus');
5367
+ el.className = 'protection-card-status ' + (status.injection_detection ? 'active' : 'inactive');
5368
+ el.textContent = status.injection_detection ? '\u2713 Active' : '\u2717 Inactive';
5369
+ }
5370
+ if (status.baseline !== undefined) {
5371
+ const el = document.getElementById('baselineStatus');
5372
+ el.className = 'protection-card-status ' + (status.baseline ? 'active' : 'inactive');
5373
+ el.textContent = status.baseline ? '\u2713 Active' : '\u2717 Inactive';
5374
+ }
5375
+ if (status.audit_trail !== undefined) {
5376
+ const el = document.getElementById('auditStatus');
5377
+ el.className = 'protection-card-status ' + (status.audit_trail ? 'active' : 'inactive');
5378
+ el.textContent = status.audit_trail ? '\u2713 Active' : '\u2717 Inactive';
5379
+ }
5380
+ }
5381
+
5382
+ // \u2500\u2500 Initialization \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
5383
+
5384
+ (async function init() {
5385
+ await exchangeSession();
5386
+ // Clean legacy ?token= from URL
5387
+ if (window.location.search.includes('token=')) {
5388
+ window.history.replaceState({}, '', window.location.pathname);
5389
+ }
5390
+ connect();
5391
+
5392
+ // Start uptime ticker
5393
+ setInterval(updateUptime, 1000);
5394
+ updateUptime();
5395
+
5396
+ // Pending request countdown timer
5397
+ setInterval(() => {
5398
+ for (const [id, req] of pendingRequests) {
5399
+ req.remaining = Math.max(0, req.remaining - 1);
5400
+ const el = document.getElementById('timer-' + id);
5401
+ if (el) {
5402
+ el.textContent = req.remaining + 's';
5403
+ }
5404
+ }
5405
+ }, 1000);
5406
+
5407
+ // Load initial status
5408
+ try {
5409
+ const resp = await fetch('/api/status', { headers: authHeaders() });
5410
+ if (resp.ok) {
5411
+ const status = await resp.json();
5412
+ if (status.baseline) updateBaseline(status.baseline);
5413
+ if (status.policy) updatePolicy(status.policy);
5414
+ }
5415
+ } catch (e) {
5416
+ // Ignore
5417
+ }
5418
+ })();
5419
+
5420
+ })();
5421
+ </script>
5422
+
5423
+ </body>
5424
+ </html>`;
5425
+ }
5426
+
5427
+ // src/principal-policy/dashboard.ts
5428
+ var SESSION_TTL_MS = 5 * 60 * 1e3;
5429
+ var MAX_SESSIONS = 1e3;
5430
+ var RATE_LIMIT_WINDOW_MS = 6e4;
5431
+ var RATE_LIMIT_GENERAL = 120;
5432
+ var RATE_LIMIT_DECISIONS = 20;
5433
+ var MAX_RATE_LIMIT_ENTRIES = 1e4;
5434
+ var DashboardApprovalChannel = class {
5435
+ config;
5436
+ pending = /* @__PURE__ */ new Map();
5437
+ sseClients = /* @__PURE__ */ new Set();
5438
+ httpServer = null;
5439
+ policy = null;
5440
+ baseline = null;
5441
+ auditLog = null;
5442
+ dashboardHTML;
5443
+ authToken;
5444
+ useTLS;
5445
+ /** SEC-012: Short-lived session store. Sessions replace URL query tokens. */
5446
+ sessions = /* @__PURE__ */ new Map();
5447
+ sessionCleanupTimer = null;
5448
+ /** Rate limiting: per-IP request tracking */
5449
+ rateLimits = /* @__PURE__ */ new Map();
5450
+ constructor(config) {
5451
+ this.config = config;
5452
+ this.authToken = config.auth_token;
5453
+ this.useTLS = !!(config.tls?.cert_path && config.tls?.key_path);
5454
+ this.dashboardHTML = generateDashboardHTML({
5455
+ timeoutSeconds: config.timeout_seconds,
5456
+ serverVersion: SANCTUARY_VERSION,
5457
+ authToken: this.authToken
5458
+ });
5459
+ this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
5460
+ }
5461
+ /**
5462
+ * Inject dependencies after construction.
5463
+ * Called from index.ts after all components are initialized.
5464
+ */
5465
+ setDependencies(deps) {
5466
+ this.policy = deps.policy;
5467
+ this.baseline = deps.baseline;
5468
+ this.auditLog = deps.auditLog;
5469
+ }
5470
+ /**
5471
+ * Start the HTTP(S) server for the dashboard.
5472
+ */
5473
+ async start() {
5474
+ return new Promise((resolve, reject) => {
5475
+ const handler = (req, res) => this.handleRequest(req, res);
5476
+ if (this.useTLS && this.config.tls) {
5477
+ const tlsOpts = {
5478
+ cert: readFileSync(this.config.tls.cert_path),
5479
+ key: readFileSync(this.config.tls.key_path)
5480
+ };
5481
+ this.httpServer = createServer$1(tlsOpts, handler);
5482
+ } else {
5483
+ this.httpServer = createServer$2(handler);
5484
+ }
5485
+ const protocol = this.useTLS ? "https" : "http";
5486
+ const baseUrl = `${protocol}://${this.config.host}:${this.config.port}`;
5487
+ this.httpServer.listen(this.config.port, this.config.host, () => {
5488
+ if (this.authToken) {
5489
+ const hint = this.authToken.slice(0, 4) + "..." + this.authToken.slice(-4);
5490
+ process.stderr.write(
5491
+ `
5492
+ Sanctuary Principal Dashboard: ${baseUrl}
5493
+ `
5494
+ );
5495
+ process.stderr.write(
5496
+ ` Auth required (token: ${hint}). Use Authorization: Bearer <TOKEN> header.
5497
+
5498
+ `
5499
+ );
5500
+ } else {
5501
+ process.stderr.write(
5502
+ `
5503
+ Sanctuary Principal Dashboard: ${baseUrl}
5504
+
5505
+ `
5506
+ );
5507
+ }
5508
+ resolve();
5509
+ });
5510
+ this.httpServer.on("error", reject);
5511
+ });
5512
+ }
5513
+ /**
5514
+ * Stop the HTTP server and clean up.
5515
+ */
5516
+ async stop() {
5517
+ for (const [, pending] of this.pending) {
5518
+ clearTimeout(pending.timer);
5519
+ pending.resolve({
5520
+ decision: "deny",
4684
5521
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4685
5522
  decided_by: "auto"
4686
5523
  });
@@ -5118,6 +5955,25 @@ data: ${JSON.stringify(data)}
5118
5955
  this.broadcastSSE("baseline-update", this.baseline.getProfile());
5119
5956
  }
5120
5957
  }
5958
+ /**
5959
+ * Broadcast a tool call event to connected dashboards.
5960
+ * Called from the gate or router when a tool is invoked.
5961
+ */
5962
+ broadcastToolCall(data) {
5963
+ this.broadcastSSE("tool-call", data);
5964
+ }
5965
+ /**
5966
+ * Broadcast a context gate decision to connected dashboards.
5967
+ */
5968
+ broadcastContextGateDecision(data) {
5969
+ this.broadcastSSE("context-gate-decision", data);
5970
+ }
5971
+ /**
5972
+ * Broadcast current protection status to connected dashboards.
5973
+ */
5974
+ broadcastProtectionStatus(data) {
5975
+ this.broadcastSSE("protection-status", data);
5976
+ }
5121
5977
  /** Get the number of pending requests */
5122
5978
  get pendingCount() {
5123
5979
  return this.pending.size;
@@ -5327,36 +6183,554 @@ var WebhookApprovalChannel = class {
5327
6183
  );
5328
6184
  return;
5329
6185
  }
5330
- const pending = this.pending.get(requestId);
5331
- if (!pending) {
5332
- res.writeHead(404, { "Content-Type": "application/json" });
5333
- res.end(
5334
- JSON.stringify({
5335
- error: "Request not found or already resolved"
5336
- })
5337
- );
5338
- return;
6186
+ const pending = this.pending.get(requestId);
6187
+ if (!pending) {
6188
+ res.writeHead(404, { "Content-Type": "application/json" });
6189
+ res.end(
6190
+ JSON.stringify({
6191
+ error: "Request not found or already resolved"
6192
+ })
6193
+ );
6194
+ return;
6195
+ }
6196
+ clearTimeout(pending.timer);
6197
+ this.pending.delete(requestId);
6198
+ const response = {
6199
+ decision: callbackPayload.decision,
6200
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
6201
+ decided_by: "human"
6202
+ };
6203
+ pending.resolve(response);
6204
+ res.writeHead(200, { "Content-Type": "application/json" });
6205
+ res.end(
6206
+ JSON.stringify({
6207
+ success: true,
6208
+ decision: callbackPayload.decision
6209
+ })
6210
+ );
6211
+ });
6212
+ }
6213
+ /** Get the number of pending requests */
6214
+ get pendingCount() {
6215
+ return this.pending.size;
6216
+ }
6217
+ };
6218
+
6219
+ // src/security/injection-detector.ts
6220
+ var ROLE_OVERRIDE_PATTERNS = [
6221
+ /ignore\s+(?:(?:previous|prior|all)\s+)?instructions/i,
6222
+ /you\s+are\s+now/i,
6223
+ /\bsystem\s*:\s+(?!working|process|design|architecture)/i,
6224
+ /forget\s+(?:everything|all|prior)/i,
6225
+ /disregard\s+(?:the\s+)?(?:previous\s+)?instructions/i,
6226
+ /new\s+instructions\s*:/i,
6227
+ /updated?\s+instructions\s*:/i
6228
+ ];
6229
+ var SECURITY_BYPASS_PATTERNS = [
6230
+ /skip\s+(?:the\s+)?(?:filter|gate|check|verify|approve)/i,
6231
+ /bypass\s+(?:the\s+)?(?:filter|gate|security|check)/i,
6232
+ /disable\s+(?:the\s+)?(?:filter|gate|approval|security|audit|log|encrypt|verify)/i,
6233
+ /do\s+not\s+(?:audit|log|encrypt|verify|approve|check|sign)/i
6234
+ ];
6235
+ var TOOL_INVOCATION_PATTERNS = [
6236
+ /sanctuary\//i,
6237
+ /concordia\//i,
6238
+ /bridge_/i,
6239
+ /handshake_/i
6240
+ ];
6241
+ var URL_PATTERN = /https?:\/\/[^\s"'<>]+/i;
6242
+ var EMAIL_PATTERN = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
6243
+ var ZERO_WIDTH_CHARS = [
6244
+ "\u200B",
6245
+ // Zero-width space
6246
+ "\u200C",
6247
+ // Zero-width non-joiner
6248
+ "\u200D",
6249
+ // Zero-width joiner
6250
+ "\uFEFF"
6251
+ // Zero-width no-break space
6252
+ ];
6253
+ var InjectionDetector = class {
6254
+ config;
6255
+ stats = {
6256
+ total_scans: 0,
6257
+ total_flags: 0,
6258
+ total_blocks: 0,
6259
+ signals_by_type: {}
6260
+ };
6261
+ constructor(config = {}) {
6262
+ this.config = {
6263
+ enabled: config.enabled ?? true,
6264
+ sensitivity: config.sensitivity ?? "medium",
6265
+ on_detection: config.on_detection ?? "escalate",
6266
+ custom_patterns: config.custom_patterns ?? []
6267
+ };
6268
+ }
6269
+ /**
6270
+ * Scan tool arguments for injection signals.
6271
+ * @param toolName Full tool name (e.g., "sanctuary/state_read")
6272
+ * @param args Tool arguments
6273
+ * @returns DetectionResult with all detected signals
6274
+ */
6275
+ scan(toolName, args) {
6276
+ this.stats.total_scans++;
6277
+ if (!this.config.enabled) {
6278
+ return {
6279
+ flagged: false,
6280
+ confidence: 0,
6281
+ signals: [],
6282
+ recommendation: "allow"
6283
+ };
6284
+ }
6285
+ const signals = [];
6286
+ const visited = /* @__PURE__ */ new Set();
6287
+ this.scanValue(args, "", toolName, signals, visited);
6288
+ const flagged = signals.length > 0;
6289
+ if (flagged) {
6290
+ this.stats.total_flags++;
6291
+ }
6292
+ for (const sig of signals) {
6293
+ this.stats.signals_by_type[sig.type] = (this.stats.signals_by_type[sig.type] ?? 0) + 1;
6294
+ }
6295
+ const recommendation = this.computeRecommendation(
6296
+ signals,
6297
+ this.config.sensitivity
6298
+ );
6299
+ if (recommendation === "block") {
6300
+ this.stats.total_blocks++;
6301
+ }
6302
+ return {
6303
+ flagged,
6304
+ confidence: this.computeConfidence(signals),
6305
+ signals,
6306
+ recommendation
6307
+ };
6308
+ }
6309
+ /**
6310
+ * Recursively scan a value and all nested values.
6311
+ */
6312
+ scanValue(value, path, toolName, signals, visited) {
6313
+ if (typeof value === "object" && value !== null) {
6314
+ if (visited.has(value)) return;
6315
+ visited.add(value);
6316
+ }
6317
+ if (typeof value === "string") {
6318
+ this.scanString(value, path, toolName, signals);
6319
+ } else if (Array.isArray(value)) {
6320
+ for (let i = 0; i < value.length; i++) {
6321
+ this.scanValue(value[i], `${path}[${i}]`, toolName, signals, visited);
6322
+ }
6323
+ } else if (typeof value === "object" && value !== null) {
6324
+ for (const [key, val] of Object.entries(value)) {
6325
+ this.scanValue(val, path ? `${path}.${key}` : key, toolName, signals, visited);
6326
+ }
6327
+ }
6328
+ }
6329
+ /**
6330
+ * Scan a single string for injection signals.
6331
+ */
6332
+ scanString(value, path, _toolName, signals) {
6333
+ if (this.isSafeField(path)) {
6334
+ return;
6335
+ }
6336
+ const location = path || "root";
6337
+ const normalized = this.normalizeConfusables(value.normalize("NFKC"));
6338
+ if (normalized !== value) {
6339
+ signals.push({
6340
+ type: "encoding_evasion",
6341
+ pattern: "unicode_normalization_delta",
6342
+ location,
6343
+ severity: "medium"
6344
+ });
6345
+ }
6346
+ for (const pattern of ROLE_OVERRIDE_PATTERNS) {
6347
+ if (pattern.test(normalized)) {
6348
+ signals.push({
6349
+ type: "role_override",
6350
+ pattern: pattern.source,
6351
+ location,
6352
+ severity: "high"
6353
+ });
6354
+ break;
6355
+ }
6356
+ }
6357
+ for (const pattern of SECURITY_BYPASS_PATTERNS) {
6358
+ if (pattern.test(normalized)) {
6359
+ signals.push({
6360
+ type: "security_bypass",
6361
+ pattern: pattern.source,
6362
+ location,
6363
+ severity: "high"
6364
+ });
6365
+ break;
6366
+ }
6367
+ }
6368
+ if (!this.isToolNameField(path)) {
6369
+ for (const pattern of TOOL_INVOCATION_PATTERNS) {
6370
+ if (pattern.test(normalized)) {
6371
+ signals.push({
6372
+ type: "tool_invocation_in_string",
6373
+ pattern: pattern.source,
6374
+ location,
6375
+ severity: "medium"
6376
+ });
6377
+ break;
6378
+ }
6379
+ }
6380
+ }
6381
+ this.detectEncodingEvasion(value, location, signals);
6382
+ this.detectDataExfiltration(value, location, signals);
6383
+ this.detectPromptStuffing(value, location, signals);
6384
+ }
6385
+ /**
6386
+ * Detect base64 strings and zero-width character evasion.
6387
+ */
6388
+ detectEncodingEvasion(value, path, signals) {
6389
+ if (value.length > 50 && /^[A-Za-z0-9+/]+={0,2}$/.test(value.trim())) {
6390
+ signals.push({
6391
+ type: "encoding_evasion",
6392
+ pattern: "base64_string",
6393
+ location: path || "root",
6394
+ severity: "medium"
6395
+ });
6396
+ }
6397
+ let zeroWidthCount = 0;
6398
+ for (const char of ZERO_WIDTH_CHARS) {
6399
+ zeroWidthCount += (value.match(new RegExp(char, "g")) || []).length;
6400
+ }
6401
+ if (zeroWidthCount > 0) {
6402
+ signals.push({
6403
+ type: "encoding_evasion",
6404
+ pattern: "zero_width_characters",
6405
+ location: path || "root",
6406
+ severity: "medium"
6407
+ });
6408
+ }
6409
+ const hasLatin = /[a-zA-Z]/.test(value);
6410
+ const hasCJK = /[\u4E00-\u9FFF\u3040-\u309F\uAC00-\uD7AF]/.test(value);
6411
+ const hasArabic = /[\u0600-\u06FF]/.test(value);
6412
+ const hasCyrillic = /[\u0400-\u04FF]/.test(value);
6413
+ const unicodeCategories = [hasLatin, hasCJK, hasArabic, hasCyrillic].filter(
6414
+ (x) => x
6415
+ ).length;
6416
+ if (unicodeCategories >= 3) {
6417
+ signals.push({
6418
+ type: "encoding_evasion",
6419
+ pattern: "unicode_category_mixing",
6420
+ location: path || "root",
6421
+ severity: "medium"
6422
+ });
6423
+ }
6424
+ }
6425
+ /**
6426
+ * Detect URLs and emails in fields that shouldn't have them.
6427
+ */
6428
+ detectDataExfiltration(value, path, signals) {
6429
+ if (this.isUrlSafeField(path)) {
6430
+ return;
6431
+ }
6432
+ if (URL_PATTERN.test(value)) {
6433
+ signals.push({
6434
+ type: "data_exfiltration",
6435
+ pattern: "url_in_string",
6436
+ location: path || "root",
6437
+ severity: "medium"
6438
+ });
6439
+ }
6440
+ if (EMAIL_PATTERN.test(value) && !this.isEmailSafeField(path)) {
6441
+ signals.push({
6442
+ type: "data_exfiltration",
6443
+ pattern: "email_in_string",
6444
+ location: path || "root",
6445
+ severity: "medium"
6446
+ });
6447
+ }
6448
+ if (value.length > 30 && value.length < 1e4 && !this.isStructuredField(path)) {
6449
+ const hasJsonContent = /\{[^}]*"[^"]*"[^}]*\}/.test(value);
6450
+ const hasXmlContent = /<[^>]+>[\s\S]*?<\/[^>]+>/.test(value);
6451
+ if (hasJsonContent || hasXmlContent) {
6452
+ signals.push({
6453
+ type: "data_exfiltration",
6454
+ pattern: "structured_data_in_string",
6455
+ location: path || "root",
6456
+ severity: "medium"
6457
+ });
6458
+ }
6459
+ }
6460
+ }
6461
+ /**
6462
+ * Detect prompt stuffing: very large strings or high repetition.
6463
+ */
6464
+ detectPromptStuffing(value, path, signals) {
6465
+ if (value.length > 10240) {
6466
+ signals.push({
6467
+ type: "prompt_stuffing",
6468
+ pattern: "large_string",
6469
+ location: path || "root",
6470
+ severity: "low"
6471
+ });
6472
+ }
6473
+ if (value.length >= 100) {
6474
+ const windowSizes = [10, 20, 50];
6475
+ for (const windowSize of windowSizes) {
6476
+ if (value.length < windowSize * 5) continue;
6477
+ const pattern = value.substring(0, windowSize);
6478
+ let count = 0;
6479
+ let idx = 0;
6480
+ while (idx <= value.length - windowSize) {
6481
+ if (value.substring(idx, idx + windowSize) === pattern) {
6482
+ count++;
6483
+ idx += windowSize;
6484
+ } else {
6485
+ idx++;
6486
+ }
6487
+ if (count >= 10) break;
6488
+ }
6489
+ if (count >= 10) {
6490
+ signals.push({
6491
+ type: "prompt_stuffing",
6492
+ pattern: "high_repetition",
6493
+ location: path || "root",
6494
+ severity: "low"
6495
+ });
6496
+ break;
6497
+ }
6498
+ }
6499
+ }
6500
+ }
6501
+ /**
6502
+ * Determine if this field is inherently safe from role override.
6503
+ */
6504
+ isSafeField(path) {
6505
+ const safePaths = [
6506
+ /\.version$/i,
6507
+ /\.timestamp$/i,
6508
+ /\.id$/i,
6509
+ /\.uuid$/i,
6510
+ /\.hash$/i,
6511
+ /\.signature$/i,
6512
+ /\.public_key$/i,
6513
+ /\.private_key$/i,
6514
+ /\.did$/i,
6515
+ /\.nonce$/i,
6516
+ /\.salt$/i,
6517
+ /\.iv$/i,
6518
+ /^ciphertext$/i,
6519
+ /^encrypted$/i
6520
+ ];
6521
+ return safePaths.some((p) => p.test(path));
6522
+ }
6523
+ /**
6524
+ * Determine if this is a tool name field (where tool refs are expected).
6525
+ */
6526
+ isToolNameField(path) {
6527
+ const toolFields = [
6528
+ /tool_name/i,
6529
+ /\.tool$/i,
6530
+ /^tool$/i,
6531
+ /operation/i
6532
+ ];
6533
+ return toolFields.some((p) => p.test(path));
6534
+ }
6535
+ /**
6536
+ * Determine if this field is safe for URLs.
6537
+ */
6538
+ isUrlSafeField(path) {
6539
+ const urlFields = [
6540
+ /url/i,
6541
+ /endpoint/i,
6542
+ /webhook/i,
6543
+ /callback/i
6544
+ ];
6545
+ return urlFields.some((p) => p.test(path));
6546
+ }
6547
+ /**
6548
+ * Determine if this field is safe for emails.
6549
+ */
6550
+ isEmailSafeField(path) {
6551
+ const emailFields = [
6552
+ /email/i,
6553
+ /contact/i,
6554
+ /recipient/i,
6555
+ /sender/i,
6556
+ /from/i,
6557
+ /to/i
6558
+ ];
6559
+ return emailFields.some((p) => p.test(path));
6560
+ }
6561
+ /**
6562
+ * Determine if this field is safe for structured data (JSON/XML).
6563
+ */
6564
+ isStructuredField(path) {
6565
+ const structuredFields = [
6566
+ /data/i,
6567
+ /payload/i,
6568
+ /body/i,
6569
+ /json/i,
6570
+ /xml/i
6571
+ ];
6572
+ return structuredFields.some((p) => p.test(path));
6573
+ }
6574
+ /**
6575
+ * SEC-032: Map common cross-script confusable characters to their Latin equivalents.
6576
+ * NFKC normalization handles fullwidth and compatibility forms, but does NOT map
6577
+ * Cyrillic/Greek lookalikes to Latin (they're distinct codepoints by design).
6578
+ * This covers the most common confusables used in injection evasion.
6579
+ */
6580
+ normalizeConfusables(value) {
6581
+ const confusables = {
6582
+ // Cyrillic → Latin
6583
+ "\u0410": "A",
6584
+ "\u0430": "a",
6585
+ // А а
6586
+ "\u0412": "B",
6587
+ "\u0432": "b",
6588
+ // В (not exact) в (not exact)
6589
+ "\u0421": "C",
6590
+ "\u0441": "c",
6591
+ // С с
6592
+ "\u0415": "E",
6593
+ "\u0435": "e",
6594
+ // Е е
6595
+ "\u041D": "H",
6596
+ "\u043D": "h",
6597
+ // Н (not exact) н (not exact)
6598
+ "\u041A": "K",
6599
+ "\u043A": "k",
6600
+ // К к (not exact)
6601
+ "\u041C": "M",
6602
+ "\u043C": "m",
6603
+ // М (not exact) м (not exact)
6604
+ "\u041E": "O",
6605
+ "\u043E": "o",
6606
+ // О о
6607
+ "\u0420": "P",
6608
+ "\u0440": "p",
6609
+ // Р р
6610
+ "\u0422": "T",
6611
+ "\u0442": "t",
6612
+ // Т (not exact) т (not exact)
6613
+ "\u0425": "X",
6614
+ "\u0445": "x",
6615
+ // Х х
6616
+ "\u0423": "Y",
6617
+ "\u0443": "y",
6618
+ // У (not exact) у
6619
+ // Greek → Latin
6620
+ "\u0391": "A",
6621
+ "\u03B1": "a",
6622
+ // Α α (not exact)
6623
+ "\u0392": "B",
6624
+ "\u03B2": "b",
6625
+ // Β β (not exact)
6626
+ "\u0395": "E",
6627
+ "\u03B5": "e",
6628
+ // Ε ε (not exact)
6629
+ "\u0397": "H",
6630
+ // Η
6631
+ "\u0399": "I",
6632
+ "\u03B9": "i",
6633
+ // Ι ι
6634
+ "\u039A": "K",
6635
+ "\u03BA": "k",
6636
+ // Κ κ
6637
+ "\u039C": "M",
6638
+ // Μ
6639
+ "\u039D": "N",
6640
+ // Ν
6641
+ "\u039F": "O",
6642
+ "\u03BF": "o",
6643
+ // Ο ο
6644
+ "\u03A1": "P",
6645
+ "\u03C1": "p",
6646
+ // Ρ ρ (not exact)
6647
+ "\u03A4": "T",
6648
+ "\u03C4": "t",
6649
+ // Τ τ (not exact)
6650
+ "\u03A5": "Y",
6651
+ "\u03C5": "y",
6652
+ // Υ υ (not exact)
6653
+ "\u03A7": "X",
6654
+ "\u03C7": "x"
6655
+ // Χ χ (not exact)
6656
+ };
6657
+ let result = value;
6658
+ if (/[^\x00-\x7F]/.test(value)) {
6659
+ const chars = [];
6660
+ for (const ch of result) {
6661
+ chars.push(confusables[ch] ?? ch);
5339
6662
  }
5340
- clearTimeout(pending.timer);
5341
- this.pending.delete(requestId);
5342
- const response = {
5343
- decision: callbackPayload.decision,
5344
- decided_at: (/* @__PURE__ */ new Date()).toISOString(),
5345
- decided_by: "human"
5346
- };
5347
- pending.resolve(response);
5348
- res.writeHead(200, { "Content-Type": "application/json" });
5349
- res.end(
5350
- JSON.stringify({
5351
- success: true,
5352
- decision: callbackPayload.decision
5353
- })
5354
- );
5355
- });
6663
+ result = chars.join("");
6664
+ }
6665
+ return result;
5356
6666
  }
5357
- /** Get the number of pending requests */
5358
- get pendingCount() {
5359
- return this.pending.size;
6667
+ /**
6668
+ * Compute confidence score based on signals.
6669
+ * More high-severity signals = higher confidence.
6670
+ */
6671
+ computeConfidence(signals) {
6672
+ if (signals.length === 0) return 0;
6673
+ let score = 0;
6674
+ let highCount = 0;
6675
+ for (const sig of signals) {
6676
+ switch (sig.severity) {
6677
+ case "high":
6678
+ highCount++;
6679
+ score += 0.35;
6680
+ break;
6681
+ case "medium":
6682
+ score += 0.15;
6683
+ break;
6684
+ case "low":
6685
+ score += 0.05;
6686
+ break;
6687
+ }
6688
+ }
6689
+ if (highCount > 1) {
6690
+ score += (highCount - 1) * 0.15;
6691
+ }
6692
+ return Math.min(score, 1);
6693
+ }
6694
+ /**
6695
+ * Compute recommendation based on signals and sensitivity.
6696
+ */
6697
+ computeRecommendation(signals, sensitivity) {
6698
+ if (signals.length === 0) return "allow";
6699
+ const highSeverity = signals.filter((s) => s.severity === "high");
6700
+ const mediumSeverity = signals.filter((s) => s.severity === "medium");
6701
+ switch (sensitivity) {
6702
+ case "low":
6703
+ return highSeverity.length > 0 ? "escalate" : "allow";
6704
+ case "medium":
6705
+ if (highSeverity.length > 0) return "block";
6706
+ return mediumSeverity.length > 0 ? "escalate" : "allow";
6707
+ case "high":
6708
+ if (highSeverity.length > 0 || mediumSeverity.length > 1) return "block";
6709
+ if (mediumSeverity.length > 0) return "block";
6710
+ return signals.length > 0 ? "escalate" : "allow";
6711
+ }
6712
+ }
6713
+ /**
6714
+ * Get statistics about scans performed.
6715
+ */
6716
+ getStats() {
6717
+ return {
6718
+ total_scans: this.stats.total_scans,
6719
+ total_flags: this.stats.total_flags,
6720
+ total_blocks: this.stats.total_blocks,
6721
+ signals_by_type: { ...this.stats.signals_by_type }
6722
+ };
6723
+ }
6724
+ /**
6725
+ * Reset statistics.
6726
+ */
6727
+ resetStats() {
6728
+ this.stats = {
6729
+ total_scans: 0,
6730
+ total_flags: 0,
6731
+ total_blocks: 0,
6732
+ signals_by_type: {}
6733
+ };
5360
6734
  }
5361
6735
  };
5362
6736
 
@@ -5366,11 +6740,15 @@ var ApprovalGate = class {
5366
6740
  baseline;
5367
6741
  channel;
5368
6742
  auditLog;
5369
- constructor(policy, baseline, channel, auditLog) {
6743
+ injectionDetector;
6744
+ onInjectionAlert;
6745
+ constructor(policy, baseline, channel, auditLog, injectionDetector, onInjectionAlert) {
5370
6746
  this.policy = policy;
5371
6747
  this.baseline = baseline;
5372
6748
  this.channel = channel;
5373
6749
  this.auditLog = auditLog;
6750
+ this.injectionDetector = injectionDetector ?? new InjectionDetector();
6751
+ this.onInjectionAlert = onInjectionAlert;
5374
6752
  }
5375
6753
  /**
5376
6754
  * Evaluate a tool call against the Principal Policy.
@@ -5382,6 +6760,48 @@ var ApprovalGate = class {
5382
6760
  async evaluate(toolName, args) {
5383
6761
  const operation = extractOperationName(toolName);
5384
6762
  this.baseline.recordToolCall(operation);
6763
+ const injectionResult = this.injectionDetector.scan(toolName, args);
6764
+ if (injectionResult.flagged) {
6765
+ this.auditLog.append("l2", `injection_detected:${operation}`, "system", {
6766
+ confidence: injectionResult.confidence,
6767
+ signals: injectionResult.signals.map((s) => ({
6768
+ type: s.type,
6769
+ location: s.location,
6770
+ severity: s.severity
6771
+ })),
6772
+ recommendation: injectionResult.recommendation
6773
+ });
6774
+ if (this.onInjectionAlert) {
6775
+ this.onInjectionAlert({
6776
+ toolName,
6777
+ result: injectionResult,
6778
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6779
+ });
6780
+ }
6781
+ if (injectionResult.recommendation === "block") {
6782
+ return {
6783
+ allowed: false,
6784
+ tier: 1,
6785
+ reason: `Blocked: prompt injection detected in "${operation}" (confidence: ${(injectionResult.confidence * 100).toFixed(0)}%)`,
6786
+ approval_required: false
6787
+ };
6788
+ }
6789
+ if (injectionResult.recommendation === "escalate") {
6790
+ return this.requestApproval(
6791
+ operation,
6792
+ 1,
6793
+ `Potential prompt injection detected in "${operation}" (confidence: ${(injectionResult.confidence * 100).toFixed(0)}%, ${injectionResult.signals.length} signal(s))`,
6794
+ {
6795
+ operation,
6796
+ injection_detection: {
6797
+ confidence: injectionResult.confidence,
6798
+ signal_count: injectionResult.signals.length,
6799
+ signal_types: [...new Set(injectionResult.signals.map((s) => s.type))]
6800
+ }
6801
+ }
6802
+ );
6803
+ }
6804
+ }
5385
6805
  if (this.policy.tier1_always_approve.includes(operation)) {
5386
6806
  return this.requestApproval(operation, 1, `"${operation}" is a Tier 1 operation (always requires approval)`, {
5387
6807
  operation,
@@ -5560,6 +6980,10 @@ var ApprovalGate = class {
5560
6980
  getBaseline() {
5561
6981
  return this.baseline;
5562
6982
  }
6983
+ /** Get the injection detector for stats/configuration access */
6984
+ getInjectionDetector() {
6985
+ return this.injectionDetector;
6986
+ }
5563
6987
  };
5564
6988
 
5565
6989
  // src/principal-policy/tools.ts
@@ -8756,9 +10180,345 @@ function matchesFieldPattern(normalizedField, pattern) {
8756
10180
  return false;
8757
10181
  }
8758
10182
 
10183
+ // src/l2-operational/context-gate-enforcer.ts
10184
+ init_encoding();
10185
+ init_hashing();
10186
+ var BUILTIN_SENSITIVE_PATTERNS = [
10187
+ "*_key",
10188
+ "*_token",
10189
+ "*_secret",
10190
+ "api_key",
10191
+ "access_token",
10192
+ "refresh_token",
10193
+ "password",
10194
+ "passwd",
10195
+ "credential*",
10196
+ "auth_*",
10197
+ "ssn",
10198
+ "social_security*",
10199
+ "tax_id*",
10200
+ "credit_card*",
10201
+ "card_number*",
10202
+ "cvv",
10203
+ "cvc",
10204
+ "private_key",
10205
+ "secret_key",
10206
+ "master_key"
10207
+ ];
10208
+ var ContextGateEnforcer = class {
10209
+ policyStore;
10210
+ auditLog;
10211
+ config;
10212
+ stats = {
10213
+ calls_inspected: 0,
10214
+ calls_bypassed: 0,
10215
+ fields_redacted: 0,
10216
+ fields_hashed: 0,
10217
+ fields_blocked: 0,
10218
+ calls_blocked: 0
10219
+ };
10220
+ constructor(policyStore, auditLog, config) {
10221
+ this.policyStore = policyStore;
10222
+ this.auditLog = auditLog;
10223
+ this.config = config;
10224
+ }
10225
+ /**
10226
+ * Wrap a tool handler to apply automatic context gating.
10227
+ *
10228
+ * The wrapped handler:
10229
+ * 1. Checks if tool should be filtered (based on bypass_prefixes)
10230
+ * 2. If not filtering, calls original handler directly
10231
+ * 3. If filtering:
10232
+ * a. Gets the active policy or falls back to built-in patterns
10233
+ * b. Calls filterContext() with tool arguments
10234
+ * c. If any field triggered "deny" and on_deny is "block", returns error
10235
+ * d. If on_deny is "redact", replaces denied fields with "[REDACTED]"
10236
+ * e. Calls original handler with filtered arguments
10237
+ * f. Logs the filtering decision
10238
+ * 4. In log_only mode: runs filter, logs what would happen, passes original args
10239
+ */
10240
+ wrapHandler(toolName, originalHandler) {
10241
+ return async (args) => {
10242
+ if (!this.config.enabled) {
10243
+ return originalHandler(args);
10244
+ }
10245
+ if (!this.shouldFilter(toolName)) {
10246
+ this.stats.calls_bypassed++;
10247
+ return originalHandler(args);
10248
+ }
10249
+ this.stats.calls_inspected++;
10250
+ const policy = this.config.default_policy_id ? await this.policyStore.get(this.config.default_policy_id) : null;
10251
+ if (policy) {
10252
+ return this.filterWithPolicy(
10253
+ toolName,
10254
+ args,
10255
+ originalHandler,
10256
+ policy
10257
+ );
10258
+ } else {
10259
+ return this.filterWithBuiltinPatterns(
10260
+ toolName,
10261
+ args,
10262
+ originalHandler
10263
+ );
10264
+ }
10265
+ };
10266
+ }
10267
+ /**
10268
+ * Filter tool arguments using an explicit policy.
10269
+ */
10270
+ async filterWithPolicy(toolName, args, originalHandler, policy) {
10271
+ const provider = this.extractProviderCategory(toolName);
10272
+ const result = filterContext(policy, provider, args);
10273
+ const deniedFields = result.decisions.filter((d) => d.action === "deny");
10274
+ if (deniedFields.length > 0) {
10275
+ if (this.config.on_deny === "block") {
10276
+ this.stats.calls_blocked++;
10277
+ this.auditLog.append(
10278
+ "l2",
10279
+ "context_gate_enforcer_block",
10280
+ "system",
10281
+ {
10282
+ tool_name: toolName,
10283
+ policy_id: policy.policy_id,
10284
+ provider,
10285
+ denied_fields: deniedFields.map((d) => d.field),
10286
+ original_context_hash: result.original_context_hash
10287
+ }
10288
+ );
10289
+ return toolResult({
10290
+ error: "context_gating_blocked",
10291
+ message: "Tool call contains fields that trigger deny action",
10292
+ tool: toolName,
10293
+ denied_fields: deniedFields.map((d) => d.field),
10294
+ recommendation: "Remove the denied fields from context or update the context-gating policy."
10295
+ });
10296
+ }
10297
+ }
10298
+ const filteredArgs = this.buildFilteredArgs(args, result.decisions);
10299
+ if (this.config.log_only) {
10300
+ this.auditLog.append(
10301
+ "l2",
10302
+ "context_gate_enforcer_log_only",
10303
+ "system",
10304
+ {
10305
+ tool_name: toolName,
10306
+ policy_id: policy.policy_id,
10307
+ provider,
10308
+ fields_total: Object.keys(args).length,
10309
+ fields_redacted: result.fields_redacted,
10310
+ fields_hashed: result.fields_hashed,
10311
+ fields_blocked: deniedFields.length,
10312
+ original_context_hash: result.original_context_hash
10313
+ }
10314
+ );
10315
+ this.stats.fields_redacted += result.fields_redacted;
10316
+ this.stats.fields_hashed += result.fields_hashed;
10317
+ this.stats.fields_blocked += deniedFields.length;
10318
+ return originalHandler(args);
10319
+ }
10320
+ this.auditLog.append(
10321
+ "l2",
10322
+ "context_gate_enforcer_filter",
10323
+ "system",
10324
+ {
10325
+ tool_name: toolName,
10326
+ policy_id: policy.policy_id,
10327
+ provider,
10328
+ fields_total: Object.keys(args).length,
10329
+ fields_redacted: result.fields_redacted,
10330
+ fields_hashed: result.fields_hashed,
10331
+ fields_blocked: deniedFields.length,
10332
+ original_context_hash: result.original_context_hash
10333
+ }
10334
+ );
10335
+ this.stats.fields_redacted += result.fields_redacted;
10336
+ this.stats.fields_hashed += result.fields_hashed;
10337
+ this.stats.fields_blocked += deniedFields.length;
10338
+ return originalHandler(filteredArgs);
10339
+ }
10340
+ /**
10341
+ * Filter tool arguments using built-in sensitive patterns.
10342
+ * This provides baseline protection when no explicit policy is configured.
10343
+ */
10344
+ async filterWithBuiltinPatterns(toolName, args, originalHandler) {
10345
+ const fieldsToRedact = [];
10346
+ const originalHash = hashToString(
10347
+ stringToBytes(JSON.stringify(args))
10348
+ );
10349
+ for (const field of Object.keys(args)) {
10350
+ if (matchesPattern(field, BUILTIN_SENSITIVE_PATTERNS)) {
10351
+ fieldsToRedact.push(field);
10352
+ }
10353
+ }
10354
+ if (fieldsToRedact.length === 0) {
10355
+ this.auditLog.append(
10356
+ "l2",
10357
+ "context_gate_enforcer_builtin_pass",
10358
+ "system",
10359
+ {
10360
+ tool_name: toolName,
10361
+ reason: "No sensitive field patterns detected"
10362
+ }
10363
+ );
10364
+ return originalHandler(args);
10365
+ }
10366
+ const filteredArgs = {};
10367
+ for (const [key, value] of Object.entries(args)) {
10368
+ if (fieldsToRedact.includes(key)) {
10369
+ filteredArgs[key] = "[REDACTED]";
10370
+ } else {
10371
+ filteredArgs[key] = value;
10372
+ }
10373
+ }
10374
+ const filteredHash = hashToString(
10375
+ stringToBytes(JSON.stringify(filteredArgs))
10376
+ );
10377
+ if (this.config.log_only) {
10378
+ this.auditLog.append(
10379
+ "l2",
10380
+ "context_gate_enforcer_builtin_log_only",
10381
+ "system",
10382
+ {
10383
+ tool_name: toolName,
10384
+ fields_redacted: fieldsToRedact.length,
10385
+ redacted_fields: fieldsToRedact,
10386
+ original_context_hash: originalHash
10387
+ }
10388
+ );
10389
+ this.stats.fields_redacted += fieldsToRedact.length;
10390
+ return originalHandler(args);
10391
+ }
10392
+ this.auditLog.append(
10393
+ "l2",
10394
+ "context_gate_enforcer_builtin_filter",
10395
+ "system",
10396
+ {
10397
+ tool_name: toolName,
10398
+ fields_redacted: fieldsToRedact.length,
10399
+ redacted_fields: fieldsToRedact,
10400
+ original_context_hash: originalHash,
10401
+ filtered_context_hash: filteredHash
10402
+ }
10403
+ );
10404
+ this.stats.fields_redacted += fieldsToRedact.length;
10405
+ return originalHandler(filteredArgs);
10406
+ }
10407
+ /**
10408
+ * Check if a tool should be filtered based on bypass prefixes.
10409
+ *
10410
+ * SEC-033: Uses exact namespace component matching, not bare startsWith().
10411
+ * A prefix of "sanctuary/" matches "sanctuary/state_read" but NOT
10412
+ * "sanctuary_evil/steal_data" (no slash boundary confusion). The prefix
10413
+ * must match exactly up to its length, and the prefix must end with "/"
10414
+ * to enforce namespace boundaries (if it doesn't, we add one for safety).
10415
+ */
10416
+ shouldFilter(toolName) {
10417
+ for (const prefix of this.config.bypass_prefixes) {
10418
+ const safePrefix = prefix.endsWith("/") ? prefix : prefix + "/";
10419
+ if (toolName === safePrefix.slice(0, -1) || toolName.startsWith(safePrefix)) {
10420
+ return false;
10421
+ }
10422
+ }
10423
+ return true;
10424
+ }
10425
+ /**
10426
+ * Extract provider category from tool name.
10427
+ * Default: "tool-api". Override for specific patterns.
10428
+ */
10429
+ extractProviderCategory(toolName) {
10430
+ if (toolName.includes("inference") || toolName.includes("llm")) {
10431
+ return "inference";
10432
+ }
10433
+ if (toolName.includes("log") || toolName.includes("telemetry")) {
10434
+ return "logging";
10435
+ }
10436
+ if (toolName.includes("analytics") || toolName.includes("metric")) {
10437
+ return "analytics";
10438
+ }
10439
+ return "tool-api";
10440
+ }
10441
+ /**
10442
+ * Build filtered arguments from filter decisions.
10443
+ */
10444
+ buildFilteredArgs(originalArgs, decisions) {
10445
+ const filtered = {};
10446
+ for (const decision of decisions) {
10447
+ switch (decision.action) {
10448
+ case "allow":
10449
+ filtered[decision.field] = originalArgs[decision.field];
10450
+ break;
10451
+ case "redact":
10452
+ filtered[decision.field] = "[REDACTED]";
10453
+ break;
10454
+ case "hash":
10455
+ filtered[decision.field] = decision.hash_value;
10456
+ break;
10457
+ case "summarize":
10458
+ filtered[decision.field] = originalArgs[decision.field];
10459
+ break;
10460
+ }
10461
+ }
10462
+ return filtered;
10463
+ }
10464
+ /**
10465
+ * Set the active policy ID.
10466
+ */
10467
+ setDefaultPolicy(policyId) {
10468
+ this.config.default_policy_id = policyId;
10469
+ }
10470
+ /**
10471
+ * Get current enforcer status and stats.
10472
+ */
10473
+ getStatus() {
10474
+ return {
10475
+ enabled: this.config.enabled,
10476
+ log_only: this.config.log_only,
10477
+ default_policy_id: this.config.default_policy_id ?? null,
10478
+ stats: { ...this.stats }
10479
+ };
10480
+ }
10481
+ /**
10482
+ * Toggle enforcer enabled state.
10483
+ */
10484
+ setEnabled(enabled) {
10485
+ this.config.enabled = enabled;
10486
+ }
10487
+ /**
10488
+ * Toggle log_only mode.
10489
+ */
10490
+ setLogOnly(logOnly) {
10491
+ this.config.log_only = logOnly;
10492
+ }
10493
+ /**
10494
+ * Reset stats counters.
10495
+ */
10496
+ resetStats() {
10497
+ this.stats = {
10498
+ calls_inspected: 0,
10499
+ calls_bypassed: 0,
10500
+ fields_redacted: 0,
10501
+ fields_hashed: 0,
10502
+ fields_blocked: 0,
10503
+ calls_blocked: 0
10504
+ };
10505
+ }
10506
+ };
10507
+
8759
10508
  // src/l2-operational/context-gate-tools.ts
8760
10509
  function createContextGateTools(storage, masterKey, auditLog) {
8761
10510
  const policyStore = new ContextGatePolicyStore(storage, masterKey);
10511
+ const enforcerConfig = {
10512
+ enabled: false,
10513
+ // Off by default; agents must explicitly enable it
10514
+ bypass_prefixes: ["sanctuary/"],
10515
+ // Skip internal tools by default
10516
+ log_only: false,
10517
+ // Filter immediately
10518
+ on_deny: "block"
10519
+ // Block requests with denied fields
10520
+ };
10521
+ const enforcer = new ContextGateEnforcer(policyStore, auditLog, enforcerConfig);
8762
10522
  const tools = [
8763
10523
  // ── Set Policy ──────────────────────────────────────────────────
8764
10524
  {
@@ -9111,9 +10871,121 @@ function createContextGateTools(storage, masterKey, auditLog) {
9111
10871
  message: policies.length === 0 ? "No context-gating policies configured. Use sanctuary/context_gate_set_policy to create one." : `${policies.length} context-gating ${policies.length === 1 ? "policy" : "policies"} configured.`
9112
10872
  });
9113
10873
  }
10874
+ },
10875
+ // ── Enforcer Status ─────────────────────────────────────────────────
10876
+ {
10877
+ name: "sanctuary/context_gate_enforcer_status",
10878
+ description: "Get the status of the automatic context gate enforcer, including enabled/disabled state, log_only mode, active policy, and statistics. The enforcer automatically filters tool arguments when enabled. Use this to monitor what the enforcer has been filtering.",
10879
+ inputSchema: {
10880
+ type: "object",
10881
+ properties: {}
10882
+ },
10883
+ handler: async () => {
10884
+ const status = enforcer.getStatus();
10885
+ auditLog.append(
10886
+ "l2",
10887
+ "context_gate_enforcer_status_query",
10888
+ "system",
10889
+ {
10890
+ enabled: status.enabled,
10891
+ log_only: status.log_only,
10892
+ default_policy_id: status.default_policy_id
10893
+ }
10894
+ );
10895
+ return toolResult({
10896
+ enforcer_status: status,
10897
+ description: "The enforcer is " + (status.enabled ? "enabled" : "disabled") + ". " + (status.log_only ? "Currently in log_only mode \u2014 filtering is logged but not applied." : "Filtering is actively applied to tool arguments."),
10898
+ guidance: status.stats.calls_inspected > 0 ? `Over ${status.stats.calls_inspected} tool calls, ${status.stats.fields_redacted} sensitive fields were redacted. Use sanctuary/context_gate_enforcer_configure to adjust settings.` : "No tool calls have been inspected yet."
10899
+ });
10900
+ }
10901
+ },
10902
+ // ── Enforcer Configuration ──────────────────────────────────────────
10903
+ {
10904
+ name: "sanctuary/context_gate_enforcer_configure",
10905
+ description: "Configure the automatic context gate enforcer. Control whether it filters tool arguments, toggle log_only mode for gradual rollout, set the active policy, and choose what to do when denied fields are encountered (block the request or redact the field). Use this to enable automatic context protection.",
10906
+ inputSchema: {
10907
+ type: "object",
10908
+ properties: {
10909
+ enabled: {
10910
+ type: "boolean",
10911
+ description: "Enable or disable the automatic enforcer. When disabled, no filtering occurs. Default: leave unchanged."
10912
+ },
10913
+ log_only: {
10914
+ type: "boolean",
10915
+ description: "Enable log_only mode: filter decisions are logged but original args are passed to handlers. Useful for monitoring before enabling actual filtering. Default: leave unchanged."
10916
+ },
10917
+ default_policy_id: {
10918
+ type: "string",
10919
+ description: "Set the default context-gating policy to use for filtering. If not set, the enforcer uses built-in sensitive field patterns. Default: leave unchanged."
10920
+ },
10921
+ on_deny: {
10922
+ type: "string",
10923
+ enum: ["block", "redact"],
10924
+ description: "Action to take when a field triggers the deny action: 'block' returns an error and prevents the call, 'redact' replaces the denied field with [REDACTED] and continues. Default: leave unchanged."
10925
+ },
10926
+ reset_stats: {
10927
+ type: "boolean",
10928
+ description: "Reset the enforcer statistics counters to zero. Default: false."
10929
+ }
10930
+ }
10931
+ },
10932
+ handler: async (args) => {
10933
+ const changes = {};
10934
+ if (args.enabled !== void 0) {
10935
+ enforcer.setEnabled(args.enabled);
10936
+ changes.enabled = args.enabled;
10937
+ }
10938
+ if (args.log_only !== void 0) {
10939
+ enforcer.setLogOnly(args.log_only);
10940
+ changes.log_only = args.log_only;
10941
+ }
10942
+ if (args.default_policy_id !== void 0) {
10943
+ const policyId = args.default_policy_id;
10944
+ const policy = await policyStore.get(policyId);
10945
+ if (!policy) {
10946
+ return toolResult({
10947
+ error: "policy_not_found",
10948
+ message: `No context-gating policy found with ID "${policyId}"`
10949
+ });
10950
+ }
10951
+ enforcer.setDefaultPolicy(policyId);
10952
+ changes.default_policy_id = policyId;
10953
+ }
10954
+ if (args.on_deny !== void 0) {
10955
+ const onDeny = args.on_deny;
10956
+ if (onDeny !== "block" && onDeny !== "redact") {
10957
+ return toolResult({
10958
+ error: "invalid_on_deny",
10959
+ message: "on_deny must be 'block' or 'redact'"
10960
+ });
10961
+ }
10962
+ enforcerConfig.on_deny = onDeny;
10963
+ changes.on_deny = onDeny;
10964
+ }
10965
+ if (args.reset_stats === true) {
10966
+ enforcer.resetStats();
10967
+ changes.reset_stats = true;
10968
+ }
10969
+ const newStatus = enforcer.getStatus();
10970
+ auditLog.append(
10971
+ "l2",
10972
+ "context_gate_enforcer_configure",
10973
+ "system",
10974
+ {
10975
+ changes,
10976
+ new_status: newStatus
10977
+ }
10978
+ );
10979
+ return toolResult({
10980
+ configured: true,
10981
+ changes,
10982
+ new_status: newStatus,
10983
+ message: Object.keys(changes).length > 0 ? "Enforcer configuration updated." : "No changes made (no configuration parameters provided)."
10984
+ });
10985
+ }
9114
10986
  }
9115
10987
  ];
9116
- return { tools, policyStore };
10988
+ return { tools, policyStore, enforcer };
9117
10989
  }
9118
10990
  function checkMemoryProtection() {
9119
10991
  const checks = {
@@ -9858,11 +11730,7 @@ async function createSanctuaryServer(options) {
9858
11730
  handshakeResults
9859
11731
  );
9860
11732
  const { tools: auditTools } = createAuditTools(config);
9861
- const { tools: contextGateTools } = createContextGateTools(
9862
- storage,
9863
- masterKey,
9864
- auditLog
9865
- );
11733
+ const { tools: contextGateTools, enforcer: contextGateEnforcer } = createContextGateTools(storage, masterKey, auditLog);
9866
11734
  const hardeningTools = createL2HardeningTools(config.storage_path, auditLog);
9867
11735
  const policy = await loadPrincipalPolicy(config.storage_path);
9868
11736
  const baseline = new BaselineTracker(storage, masterKey);
@@ -9900,9 +11768,27 @@ async function createSanctuaryServer(options) {
9900
11768
  } else {
9901
11769
  approvalChannel = new StderrApprovalChannel(policy.approval_channel);
9902
11770
  }
9903
- const gate = new ApprovalGate(policy, baseline, approvalChannel, auditLog);
11771
+ const injectionDetector = new InjectionDetector({
11772
+ enabled: true,
11773
+ sensitivity: "medium",
11774
+ on_detection: "escalate"
11775
+ });
11776
+ const onInjectionAlert = dashboard ? (alert) => {
11777
+ dashboard.broadcastSSE("injection-alert", {
11778
+ tool: alert.toolName,
11779
+ confidence: alert.result.confidence,
11780
+ signals: alert.result.signals.map((s) => ({
11781
+ type: s.type,
11782
+ location: s.location,
11783
+ severity: s.severity
11784
+ })),
11785
+ recommendation: alert.result.recommendation,
11786
+ timestamp: alert.timestamp
11787
+ });
11788
+ } : void 0;
11789
+ const gate = new ApprovalGate(policy, baseline, approvalChannel, auditLog, injectionDetector, onInjectionAlert);
9904
11790
  const policyTools = createPrincipalPolicyTools(policy, baseline, auditLog);
9905
- const allTools = [
11791
+ let allTools = [
9906
11792
  ...l1Tools,
9907
11793
  ...l2Tools,
9908
11794
  ...l3Tools,
@@ -9917,6 +11803,10 @@ async function createSanctuaryServer(options) {
9917
11803
  ...hardeningTools,
9918
11804
  manifestTool
9919
11805
  ];
11806
+ allTools = allTools.map((tool) => ({
11807
+ ...tool,
11808
+ handler: contextGateEnforcer.wrapHandler(tool.name, tool.handler)
11809
+ }));
9920
11810
  const server = createServer(allTools, { gate });
9921
11811
  await saveConfig(config);
9922
11812
  const saveBaseline = () => {