@sanctuary-framework/mcp-server 0.4.2 → 0.5.0

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