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