sightingdb 0.5.7

A database designed for Sightings, a technique to count items
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SightingDB — management</title>
<style>
  :root {
    --bg: #ffffff; --fg: #1b1f24; --muted: #5c6570; --line: #d9dee4;
    --panel: #f6f8fa; --accent: #0b5fff; --danger: #b3261e; --mono: ui-monospace, SFMono-Regular, Menlo, monospace;
  }
  @media (prefers-color-scheme: dark) {
    :root { --bg: #14171a; --fg: #e6e9ec; --muted: #9aa4af; --line: #2b3138;
            --panel: #1b1f24; --accent: #6f9dff; --danger: #ff6b5e; }
  }
  * { box-sizing: border-box; }
  body { margin: 0; background: var(--bg); color: var(--fg);
         font: 14px/1.5 system-ui, -apple-system, Segoe UI, sans-serif; }
  header { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;
           padding: .7rem 1rem; border-bottom: 1px solid var(--line); background: var(--panel); }
  header h1 { font-size: 1rem; margin: 0; font-weight: 600; }
  header .spacer { flex: 1; }
  main { padding: 1rem; max-width: 1200px; margin: 0 auto; }
  a { color: var(--accent); }
  button { font: inherit; padding: .35rem .7rem; border: 1px solid var(--line);
           background: var(--bg); color: var(--fg); border-radius: 6px; cursor: pointer; }
  button:hover:not(:disabled) { border-color: var(--accent); }
  button:disabled { opacity: .45; cursor: default; }
  input, select { font: inherit; padding: .35rem .6rem; border: 1px solid var(--line);
          border-radius: 6px; background: var(--bg); color: var(--fg); }
  table { width: 100%; border-collapse: collapse; }
  th, td { text-align: left; padding: .4rem .6rem; border-bottom: 1px solid var(--line);
           vertical-align: top; }
  th { color: var(--muted); font-weight: 600; white-space: nowrap; }
  td.v, td.n { font-family: var(--mono); word-break: break-all; }
  tbody tr:hover { background: var(--panel); }
  .row { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; margin-bottom: .8rem; }
  .muted { color: var(--muted); }
  .err { color: var(--danger); }
  .crumbs { font-family: var(--mono); font-size: .9rem; }
  .crumbs a { text-decoration: none; }
  .crumbs a:hover { text-decoration: underline; }
  textarea { font: inherit; padding: .35rem .6rem; border: 1px solid var(--line);
             border-radius: 6px; background: var(--bg); color: var(--fg); }
  .kind { color: var(--muted); font-size: .85rem; }
  .cards { display: grid; gap: .6rem; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); }
  .card { border: 1px solid var(--line); border-radius: 8px; padding: .6rem .8rem; background: var(--panel); }
  .card h3 { margin: 0 0 .3rem; font-size: .8rem; text-transform: uppercase;
             letter-spacing: .04em; color: var(--muted); }
  .card p { margin: 0; font-family: var(--mono); word-break: break-all; }
  #chart { width: 100%; height: 320px; }
  #graph { width: 100%; height: 420px; }
  .scroll { overflow-x: auto; }
  dialog { border: 1px solid var(--line); border-radius: 10px; background: var(--bg);
           color: var(--fg); padding: 1.2rem; max-width: 420px; }
  dialog::backdrop { background: rgba(0,0,0,.45); }
  .hidden { display: none !important; }
  .chip { display: inline-block; font-family: var(--mono); font-size: .82rem;
          border: 1px solid var(--line); border-radius: 999px; padding: .05rem .5rem;
          margin: 0 .2rem .2rem 0; background: var(--bg); }
  .chip.all { border-style: dashed; }
  .chip.none { color: var(--muted); border: none; padding-left: 0; }
  td.actions { white-space: nowrap; }
  td.actions button { padding: .2rem .5rem; margin-right: .3rem; }
  button.danger { border-color: var(--danger); color: var(--danger); }
  dialog.wide { max-width: 640px; }
  .grant-row { display: flex; gap: .5rem; align-items: center; margin-bottom: .35rem; }
  .grant-row input[type=text] { flex: 1; }
  .grant-row label { font-size: .85rem; color: var(--muted); display: flex;
                     gap: .25rem; align-items: center; }
  fieldset { border: 1px solid var(--line); border-radius: 8px; margin: .8rem 0; }
  legend { color: var(--muted); font-size: .8rem; text-transform: uppercase;
           letter-spacing: .04em; padding: 0 .3rem; }
</style>
</head>
<body>
<header>
  <h1>SightingDB</h1>
  <span class="crumbs" id="crumbs"></span>
  <span class="spacer"></span>
  <span class="muted" id="version"></span>
  <button id="nav-browse">Browse</button>
  <button id="nav-keys">Keys</button>
  <button id="nav-config">Configuration</button>
  <button id="signout">Sign out</button>
</header>

<main>
  <div id="error" class="err"></div>

  <!-- One level of the namespace tree -->
  <section id="view-namespaces">
    <div class="row">
      <button id="ns-up" title="Up one level">↑ Up</button>
      <input id="ns-filter" placeholder="Filter this level" size="24">
      <label class="muted" style="display:flex;gap:.3rem;align-items:center">
        <input type="checkbox" id="ns-deep"> search everywhere
      </label>
      <span class="muted" id="ns-count"></span>
      <span class="spacer"></span>
      <button id="ns-new">New namespace</button>
      <button id="ns-add">Add values</button>
      <button id="ns-export" title="Download this namespace as a STIX 2.1 bundle">Export STIX</button>
      <button id="ns-prev">Previous</button>
      <button id="ns-next">Next</button>
    </div>
    <div class="scroll"><table>
      <thead><tr>
        <th>Name</th><th>Holds</th><th>In memory</th><th>Tier</th>
      </tr></thead>
      <tbody id="ns-rows"></tbody>
    </table></div>
    <p class="muted" id="ns-empty"></p>
    <p class="muted">A namespace is a path, so <code>feeds/misp/ips</code> browses
       like folders: <b>folder</b> means other namespaces sit underneath it,
       <b>namespace</b> means it holds values of its own, and a path can be both.
       A tier applies to the whole top-level namespace, so changing it for
       <code>myorg/one</code> changes <code>myorg</code> and everything under it.
       <b>hot</b> stays in memory; <b>warm</b> is dropped once untouched for the
       configured window; <b>cold</b> is dropped at the next sweep. Evicted data
       is read back automatically when it is next used.</p>
  </section>

  <!-- Values held by the namespace being browsed -->
  <section id="view-values" class="hidden">
    <h3 id="v-title">Values</h3>
    <div class="row">
      <input id="v-filter" placeholder="Filter values" size="30">
      <span class="muted" id="v-count"></span>
      <span class="spacer"></span>
      <button id="v-prev">Previous</button>
      <button id="v-next">Next</button>
    </div>
    <div class="scroll"><table>
      <thead><tr>
        <th>Value</th><th>Count</th><th>First seen</th><th>Last seen</th>
        <th>Consensus</th><th>TTL</th>
      </tr></thead>
      <tbody id="v-rows"></tbody>
    </table></div>
    <p class="muted" id="v-empty"></p>
  </section>

  <!-- API keys -->
  <section id="view-keys" class="hidden">
    <div class="row">
      <button id="k-new">New key</button>
      <span class="muted" id="k-count"></span>
      <span class="spacer"></span>
      <span class="muted" id="k-readonly"></span>
    </div>
    <div class="scroll"><table>
      <thead><tr>
        <th>API key</th><th>Admin</th><th>Read</th><th>Write</th><th></th>
      </tr></thead>
      <tbody id="k-rows"></tbody>
    </table></div>
  </section>

  <!-- Server configuration, read-only -->
  <section id="view-config" class="hidden">
    <p class="muted">Read from the configuration file at startup. Change it there
       and restart; only API keys are editable here.</p>
    <div class="scroll"><table><tbody id="c-rows"></tbody></table></div>
  </section>

  <!-- One value, with its histogram -->
  <section id="view-value" class="hidden">
    <div class="row">
      <button id="d-back">← Back</button>
      <strong class="crumbs" id="d-value"></strong>
    </div>
    <div class="cards" id="d-cards"></div>
    <div class="row" style="margin-top:.8rem">
      <label class="muted" style="flex:1">Tags<br>
        <input id="d-tags" type="text" style="width:100%"
               placeholder="stix-type:ipv4-addr, tlp:amber">
      </label>
      <button id="d-save-tags" style="align-self:flex-end">Save tags</button>
    </div>
    <p class="muted">Comma separated, and replacing rather than merging: this is
       where a wrong tag comes off. What each one means to the STIX export is in
       the README.</p>
    <h3>Sightings over time</h3>
    <p class="muted" id="d-nostats"></p>
    <div id="chart"></div>
    <h3>Where else this value has been seen</h3>
    <p class="muted" id="d-relations"></p>
    <div id="graph"></div>
    <p class="muted">Each namespace holding this value is joined to it; the
       folders above them are drawn too, so namespaces sharing a path sit
       together. Colour is the top-level namespace, ◆ is the value itself,
       ▭ a folder and ● a namespace. Drag a node to pull the graph about,
       scroll to zoom, and click a namespace to browse it.</p>
  </section>
</main>

<dialog id="login">
  <form method="dialog" id="login-form">
    <h2 style="margin-top:0;font-size:1.05rem">Management access</h2>
    <p class="muted">Enter an API key holding the <code>admin</code> grant.
       On a fresh install that is <code>changeme</code>.</p>
    <p><input id="key" type="password" placeholder="API key" size="32" autofocus></p>
    <p class="err" id="login-error"></p>
    <button type="submit">Sign in</button>
  </form>
</dialog>

<dialog id="ns-editor">
  <form method="dialog" id="ns-form">
    <h2 style="margin-top:0;font-size:1.05rem">New namespace</h2>
    <p class="muted" id="nn-where"></p>
    <p><input id="nn-name" type="text" placeholder="name" size="32" autofocus></p>
    <p class="muted">Use <code>/</code> for subfolders: <code>misp/ips</code>
       creates the whole path at once. It starts out empty; add values to it
       whenever you like.</p>
    <p class="crumbs" id="nn-preview"></p>
    <p class="err" id="nn-error"></p>
    <div class="row">
      <button type="submit">Create</button>
      <button type="button" id="nn-cancel">Cancel</button>
    </div>
  </form>
</dialog>

<dialog id="value-editor" class="wide">
  <form method="dialog" id="value-form">
    <h2 style="margin-top:0;font-size:1.05rem">Add values</h2>

    <p><label class="muted">Namespace<br>
      <input id="av-namespace" type="text" size="42" placeholder="feeds/misp/ips">
    </label></p>

    <p><label class="muted">Values, one per line<br>
      <textarea id="av-values" rows="8" style="width:100%;font-family:var(--mono)"
                placeholder="8.8.8.8&#10;1.1.1.1"></textarea>
    </label></p>

    <p><label class="muted">Tags, comma separated<br>
      <input id="av-tags" type="text" size="42"
             placeholder="stix-type:ipv4-addr, tlp:amber, confidence:80">
    </label></p>

    <div class="row">
      <label class="muted">TTL in seconds
        <input id="av-ttl" type="number" min="0" step="1" size="8" placeholder="none">
      </label>
      <label class="muted">Seen at
        <input id="av-when" type="datetime-local">
      </label>
    </div>
    <p class="muted">Leave the TTL blank to keep whatever expiry a value already
       had, or set 0 to clear it. Leave the time blank to record the values as
       seen now. Writing a namespace that does not exist creates it. Tags are
       merged with whatever each value already carried, and are what the STIX
       export uses to say what a value <em>is</em> — see the tag vocabulary in
       the README.</p>

    <p class="err" id="av-error"></p>
    <div class="row">
      <button type="submit" id="av-save">Add</button>
      <button type="button" id="av-cancel">Cancel</button>
    </div>
  </form>
</dialog>

<dialog id="key-editor" class="wide">
  <form method="dialog" id="key-form">
    <h2 style="margin-top:0;font-size:1.05rem" id="ke-title">New API key</h2>

    <div class="row">
      <input id="ke-key" type="text" placeholder="API key" size="42">
      <button type="button" id="ke-generate">Generate</button>
    </div>
    <p class="muted" style="margin-top:0">
      No spaces, quotes, <code>=</code>, <code>:</code> or <code>,</code>.
    </p>

    <fieldset>
      <legend>Namespaces</legend>
      <div id="ke-grants"></div>
      <button type="button" id="ke-add">Add namespace</button>
      <p class="muted">Leave a namespace blank to grant every namespace. Prefixes
         match whole path segments, so <code>feeds/misp</code> covers
         <code>feeds/misp/ips</code> but not <code>feeds/misp-internal</code>.</p>
    </fieldset>

    <fieldset>
      <legend>Management</legend>
      <label style="display:flex;gap:.4rem;align-items:center">
        <input type="checkbox" id="ke-admin">
        Can use this management interface
      </label>
    </fieldset>

    <p class="err" id="ke-error"></p>
    <div class="row">
      <button type="submit">Save</button>
      <button type="button" id="ke-cancel">Cancel</button>
    </div>
  </form>
</dialog>

<script src="/_management/echarts.min.js"></script>
<script>
"use strict";

const PAGE = 50;
const state = {
  key: sessionStorage.getItem("sightingdb.key") || "",
  // The path being browsed. It is a folder and a namespace at the same time:
  // `feeds` may hold values of its own and still have `feeds/ips` under it.
  namespace: null,
  keys: [], editing: null,
  nsOffset: 0, nsTotal: 0,
  vOffset: 0, vTotal: 0,
  chart: null, graph: null,
  // The value the detail view is showing, so its tags can be saved back.
  value: null,
};

const VIEWS = ["view-namespaces", "view-values", "view-value", "view-keys", "view-config"];
const $ = (id) => document.getElementById(id);
const show = (...ids) => {
  for (const v of VIEWS) $(v).classList.toggle("hidden", !ids.includes(v));
};
const fmtTime = (unix) =>
  !unix ? "" : new Date(unix * 1000).toISOString().replace("T", " ").replace(".000Z", "Z");

function setError(message) { $("error").textContent = message || ""; }

/** Every call carries the key; a 401/403 sends us back to the login dialog. */
async function api(path, method = "GET", body) {
  const options = { method, headers: { Authorization: state.key } };
  if (body !== undefined) {
    options.headers["Content-Type"] = "application/json";
    options.body = JSON.stringify(body);
  }
  const res = await fetch(path, options);
  if (res.status === 401 || res.status === 403) {
    signOut("That key was not accepted.");
    throw new Error("unauthorized");
  }
  if (!res.ok) {
    const failure = await res.json().catch(() => ({}));
    // The status is carried along: a namespace that holds no values of its own
    // answers 404, which is a fact about the path rather than an error to show.
    const error = new Error(failure.message || `${res.status} ${res.statusText}`);
    error.status = res.status;
    error.body = failure;
    throw error;
  }
  return res.json();
}

// --- routing ---------------------------------------------------------------
// The namespace lives in the URL, so /_management/feeds/ips/ is a real link.

function namespaceFromPath() {
  const path = decodeURIComponent(location.pathname);
  const rest = path.replace(/^\/_management\/?/, "");
  return rest.length ? rest : null;
}

function go(namespace, push = true) {
  state.namespace = namespace || null;
  state.vOffset = 0;
  state.nsOffset = 0;
  $("ns-filter").value = "";
  $("v-filter").value = "";
  if (push) {
    const url = namespace ? `/_management/${namespace}` : "/_management/";
    history.pushState({ namespace }, "", url);
  }
  render();
}

window.addEventListener("popstate", () => {
  state.namespace = namespaceFromPath();
  render();
});

function render() {
  setError("");
  drawCrumbs();
  $("ns-up").disabled = !state.namespace;
  // A path shows what is under it and what it holds at once, so both tables
  // are on screen together; the root has no values of its own to show.
  show(...(state.namespace ? ["view-namespaces", "view-values"] : ["view-namespaces"]));
  loadListing();
  if (state.namespace) loadValues();
}

/** Each segment of the path is a link back to that level. */
function drawCrumbs() {
  const crumbs = $("crumbs");
  crumbs.replaceChildren();

  const root = document.createElement("a");
  root.href = "/_management/";
  root.textContent = "/";
  root.onclick = (e) => { e.preventDefault(); go(null); };
  crumbs.append(root);

  if (!state.namespace) return;
  const segments = state.namespace.split("/").filter(Boolean);
  segments.forEach((segment, i) => {
    const path = segments.slice(0, i + 1).join("/");
    const a = document.createElement("a");
    a.href = `/_management/${path}`;
    a.textContent = segment;
    a.onclick = (e) => { e.preventDefault(); go(path); };
    crumbs.append(a, i < segments.length - 1 ? "/" : "");
  });
}

/** The parent path, or null at the top. */
function parentOf(namespace) {
  const segments = (namespace || "").split("/").filter(Boolean);
  segments.pop();
  return segments.length ? segments.join("/") : null;
}

// --- namespaces ------------------------------------------------------------

/** Browsing walks one level at a time; searching everywhere is a flat list. */
function searching() {
  return $("ns-deep").checked && $("ns-filter").value.trim() !== "";
}

function loadListing() {
  return searching() ? loadSearch() : loadTree();
}

async function loadTree() {
  try {
    const path = encodeURIComponent(state.namespace || "");
    const q = encodeURIComponent($("ns-filter").value.trim());
    const page = await api(
      `/_management/api/tree?path=${path}&q=${q}&offset=${state.nsOffset}&limit=${PAGE}`);
    state.nsTotal = page.total;

    $("ns-rows").replaceChildren(...page.items.map((item) => {
      // A folder is named by its segment; what it holds says whether there is
      // anything under it, values in it, or both.
      const holds = [];
      if (item.namespace) holds.push("namespace");
      if (item.descendants) holds.push(`${item.descendants} below`);
      return namespaceRow(item, item.name + (item.descendants ? "/" : ""),
                          holds.join(", ") || "folder", item.path);
    }));

    $("ns-empty").textContent = page.total ? "" : (
      $("ns-filter").value.trim()
        ? "Nothing here matches that filter."
        : state.namespace
          ? "Nothing below this namespace."
          : "No namespaces yet. Create one, or write a sighting to /w/<namespace>.");

    paging("ns", page);
  } catch (e) { setError(e.message); }
}

/** The flat search: whole namespace names, wherever they are. */
async function loadSearch() {
  try {
    const q = encodeURIComponent($("ns-filter").value.trim());
    const page = await api(
      `/_management/api/namespaces?q=${q}&offset=${state.nsOffset}&limit=${PAGE}`);
    state.nsTotal = page.total;

    $("ns-rows").replaceChildren(...page.items.map((item) =>
      namespaceRow(item, item.namespace, "namespace", item.namespace)));

    $("ns-empty").textContent = page.total ? "" : "No namespace matches that.";
    paging("ns", page);
  } catch (e) { setError(e.message); }
}

/**
 * One row of the listing. The tier belongs to the top-level namespace, so the
 * control is labelled with the shard it will actually change.
 */
function namespaceRow(item, label, holds, path) {
  const tr = document.createElement("tr");

  const name = document.createElement("td");
  name.className = "n";
  const a = document.createElement("a");
  a.href = `/_management/${path}`;
  a.textContent = label;
  a.onclick = (e) => { e.preventDefault(); go(path); };
  name.append(a);

  const kind = document.createElement("td");
  kind.className = "kind";
  kind.textContent = holds;

  const resident = document.createElement("td");
  resident.textContent = item.resident ? "yes" : "on disk";
  if (!item.resident) resident.className = "muted";

  const tier = document.createElement("td");
  const select = document.createElement("select");
  for (const option of ["hot", "warm", "cold"]) {
    const o = document.createElement("option");
    o.value = o.textContent = option;
    o.selected = option === item.tier;
    select.append(o);
  }
  select.title = `applies to ${item.shard}`;
  select.onchange = () => setTier(item.shard, select.value, select);
  const shard = document.createElement("span");
  shard.className = "muted";
  shard.textContent = ` ${item.shard}`;
  tier.append(select, shard);

  tr.append(name, kind, resident, tier);
  return tr;
}

/** Shared by both listings and by the value table. */
function paging(prefix, page) {
  const from = page.total ? page.offset + 1 : 0;
  $(`${prefix}-count`).textContent =
    `${from}\u2013${page.offset + page.items.length} of ${page.total}`;
  $(`${prefix}-prev`).disabled = page.offset === 0;
  $(`${prefix}-next`).disabled = page.offset + page.items.length >= page.total;
}

/**
 * Tiers are per top-level namespace, so one change moves every row sharing it.
 * The list is reloaded rather than patched so those rows agree again.
 */
async function setTier(shard, tier, control) {
  control.disabled = true;
  try {
    await api("/_management/api/tier", "POST", { shard, tier });
    await loadListing();
  } catch (e) {
    setError(e.message);
    control.disabled = false;
    loadListing();
  }
}

// --- creating namespaces and adding values ---------------------------------

function openNamespaceEditor() {
  $("nn-name").value = "";
  $("nn-error").textContent = "";
  $("nn-where").textContent = state.namespace
    ? `Created under /${state.namespace}.`
    : "Created at the top level.";
  previewNamespace();
  $("ns-editor").showModal();
}

/** Shows the full path as it is typed, so a slash is never a surprise. */
function previewNamespace() {
  const name = $("nn-name").value.trim().replace(/^\/+|\/+$/g, "");
  const path = [state.namespace, name].filter(Boolean).join("/");
  $("nn-preview").textContent = path ? `/${path}` : "";
}

async function createNamespace() {
  const name = $("nn-name").value.trim();
  const namespace = [state.namespace, name].filter(Boolean).join("/");
  try {
    const created = await api("/_management/api/namespaces", "POST", { namespace });
    $("ns-editor").close();
    // Straight into it, the way a file manager opens a folder it just made.
    go(created.namespace);
  } catch (e) {
    // Kept open so a rejected name can be corrected rather than retyped.
    $("nn-error").textContent = e.message;
  }
}

function openValueEditor() {
  $("av-namespace").value = state.namespace || "";
  $("av-values").value = "";
  $("av-tags").value = "";
  $("av-ttl").value = "";
  $("av-when").value = "";
  $("av-error").textContent = "";
  $("value-editor").showModal();
}

async function addValues() {
  const namespace = $("av-namespace").value.trim();
  const values = $("av-values").value.split(/\r?\n/);
  const body = { namespace, values, tags: $("av-tags").value.trim() };

  const ttl = $("av-ttl").value.trim();
  if (ttl !== "") body.ttl = Number(ttl);
  // The picker works in local time; the server counts in Unix seconds.
  const when = $("av-when").value;
  if (when) {
    const parsed = Date.parse(when);
    if (Number.isNaN(parsed)) {
      $("av-error").textContent = "That is not a time I can read.";
      return;
    }
    body.timestamp = Math.floor(parsed / 1000);
  }

  $("av-save").disabled = true;
  try {
    const report = await api("/_management/api/values", "POST", body);
    $("value-editor").close();
    if (report.namespace === state.namespace) {
      state.vOffset = 0;
      loadValues();
      loadListing();
    } else {
      go(report.namespace);
    }
    // A partial success is worth saying out loud: the rest did land.
    setError(report.errors && report.errors.length
      ? `Added ${report.written}; ${report.errors.length} rejected  ` +
        report.errors.slice(0, 3).map((e) => `"${e.value}": ${e.error}`).join("; ")
      : "");
  } catch (e) {
    const rejected = (e.body && e.body.errors) || [];
    $("av-error").textContent = rejected.length
      ? rejected.slice(0, 3).map((r) => `"${r.value}": ${r.error}`).join("; ")
      : e.message;
  } finally {
    $("av-save").disabled = false;
  }
}

// --- values ----------------------------------------------------------------

async function loadValues() {
  $("v-title").textContent = `Values in /${state.namespace}`;
  try {
    const ns = encodeURIComponent(state.namespace);
    const q = encodeURIComponent($("v-filter").value.trim());
    const page = await api(
      `/_management/api/values?namespace=${ns}&q=${q}&offset=${state.vOffset}&limit=${PAGE}`);
    state.vTotal = page.total;

    $("v-rows").replaceChildren(...page.items.map((item) => {
      const tr = document.createElement("tr");
      const cells = [
        ["v", item.value, true],
        ["", String(item.count)],
        ["", fmtTime(item.first_seen)],
        ["", fmtTime(item.last_seen)],
        ["", String(item.consensus)],
        ["", item.ttl ? `${item.ttl}s` : ""],
      ];
      for (const [cls, text, link] of cells) {
        const td = document.createElement("td");
        if (cls) td.className = cls;
        if (link) {
          const a = document.createElement("a");
          a.href = "#";
          a.textContent = text;
          a.onclick = (e) => { e.preventDefault(); loadValue(text); };
          td.append(a);
        } else {
          td.textContent = text;
        }
        tr.append(td);
      }
      return tr;
    }));

    $("v-empty").textContent = page.total ? "" : (
      $("v-filter").value.trim() ? "No value here matches that filter."
                                 : "This namespace holds no values yet.");
    paging("v", page);
  } catch (e) {
    // 404 means the path is a folder above other namespaces without being one
    // itself, which is a normal thing to be, not a failure.
    if (e.status === 404) {
      $("v-rows").replaceChildren();
      $("v-count").textContent = "";
      $("v-empty").textContent =
        "Nothing is stored at this path itself — it only holds other namespaces.";
      $("v-prev").disabled = $("v-next").disabled = true;
      return;
    }
    setError(e.message);
  }
}

// --- one value, with the histogram ----------------------------------------

async function loadValue(value) {
  show("view-value");
  setError("");
  $("d-value").textContent = value;
  try {
    const ns = encodeURIComponent(state.namespace);
    const item = await api(
      `/_management/api/value?namespace=${ns}&value=${encodeURIComponent(value)}`);

    state.value = item.value;
    $("d-tags").value = item.tags || "";

    const cards = [
      ["Count", item.count],
      ["First seen", fmtTime(item.first_seen)],
      ["Last seen", fmtTime(item.last_seen)],
      ["Consensus", `${item.consensus} namespace(s)`],
      ["TTL", item.ttl ? `${item.ttl}s` : "none"],
      ["Observable", stixTypeOf(item) || "not recognised"],
    ];
    $("d-cards").replaceChildren(...cards.map(([label, text]) => {
      const div = document.createElement("div");
      div.className = "card";
      const h = document.createElement("h3");
      h.textContent = label;
      const p = document.createElement("p");
      p.textContent = String(text);
      div.append(h, p);
      return div;
    }));

    drawHistogram(item.stats || {});
    loadRelations(value);
  } catch (e) { setError(e.message); }
}

/**
 * A value usually lives in more than one namespace — that is what consensus
 * counts — and which ones they are says more than the number does.
 */
async function loadRelations(value) {
  try {
    const found = await api(`/_management/api/sightings?value=${encodeURIComponent(value)}`);

    const shown = found.items.length;
    const notes = [`Seen in ${shown} namespace(s)`];
    // Consensus counts every namespace, including ones this key cannot read,
    // so the difference is worth naming rather than quietly dropping.
    if (found.consensus > shown) {
      notes.push(`${found.consensus - shown} more hold it that this key cannot read`);
    }
    if (found.truncated) notes.push("more were found than are drawn");
    $("d-relations").textContent = notes.join("") + ".";

    drawRelations(value, found.items);
  } catch (e) { setError(e.message); }
}

/**
 * The graph is the value in the middle, every namespace holding it around the
 * outside, and the folders in between, so `feeds/misp/ips` and
 * `feeds/misp/domains` visibly hang off the same branch. Colour is the
 * top-level namespace and shape is what a node is.
 */
function drawRelations(value, items) {
  if (!state.graph) state.graph = echarts.init($("graph"), null, { renderer: "canvas" });
  if (!items.length) { state.graph.clear(); return; }

  const dark = matchMedia("(prefers-color-scheme: dark)").matches;
  const fg = dark ? "#e6e9ec" : "#1b1f24";
  const accent = dark ? "#6f9dff" : "#0b5fff";

  // One category per top-level namespace, which is what gives each branch its
  // colour and the legend its entries.
  const categories = [{ name: "this value" }];
  const categoryOf = new Map();
  for (const item of items) {
    if (!categoryOf.has(item.shard)) {
      categoryOf.set(item.shard, categories.length);
      categories.push({ name: item.shard });
    }
  }

  const nodes = new Map();
  const links = [];
  const node = (id, extra) => {
    if (!nodes.has(id)) nodes.set(id, { id, ...extra });
    return nodes.get(id);
  };

  node("\u0000value", {
    name: value.length > 40 ? `${value.slice(0, 39)}` : value,
    category: 0,
    symbol: "diamond",
    symbolSize: 46,
    label: { fontWeight: "bold" },
    kind: "value",
  });

  const counts = items.map((item) => item.count);
  const busiest = Math.max(...counts, 1);
  for (const item of items) {
    const segments = item.namespace.split("/").filter(Boolean);
    const category = categoryOf.get(item.shard);

    // The folders on the way down, each linked to the one above it.
    let parent = null;
    for (let i = 0; i < segments.length; i++) {
      const path = segments.slice(0, i + 1).join("/");
      const leaf = i === segments.length - 1;
      const existing = nodes.get(path);
      if (!existing || (leaf && existing.kind === "folder")) {
        // Sized by how often the value was seen there, so a busy namespace
        // stands out; folders stay small.
        const size = leaf ? 18 + 26 * (item.count / busiest) : 14;
        nodes.set(path, {
          id: path,
          name: segments[i],
          category,
          symbol: leaf ? "circle" : "roundRect",
          symbolSize: size,
          kind: leaf ? "namespace" : "folder",
          path,
          count: leaf ? item.count : undefined,
          first_seen: leaf ? item.first_seen : undefined,
          last_seen: leaf ? item.last_seen : undefined,
          // The namespace we came from is worth spotting in the crowd.
          itemStyle: leaf && path === state.namespace
            ? { borderColor: accent, borderWidth: 3 }
            : undefined,
        });
      }
      if (parent) links.push({ source: parent, target: path, kind: "path" });
      parent = path;
    }

    // And the value itself, joined to the namespace holding it.
    links.push({
      source: "\u0000value",
      target: item.namespace,
      kind: "sighting",
      lineStyle: { type: "dashed", opacity: 0.65 },
    });
  }

  // Two branches can end in the same segment — `feeds/misp/ips` and
  // `feeds/otx/ips` are both "ips" — so those are labelled with the whole path
  // rather than left ambiguous.
  const seenNames = new Map();
  for (const n of nodes.values()) {
    seenNames.set(n.name, (seenNames.get(n.name) || 0) + 1);
  }
  for (const n of nodes.values()) {
    if (n.path && seenNames.get(n.name) > 1) n.name = n.path;
  }

  state.graph.setOption({
    backgroundColor: "transparent",
    textStyle: { color: fg },
    legend: [{ data: categories.map((c) => c.name), textStyle: { color: fg }, top: 0 }],
    tooltip: {
      formatter: (p) => {
        if (p.dataType === "edge") return "";
        const d = p.data;
        if (d.kind === "value") return `<b>${escapeHtml(value)}</b>`;
        if (d.kind === "folder") return `${escapeHtml(d.path)}<br>folder`;
        return `${escapeHtml(d.path)}<br><b>${d.count}</b> sighting(s)<br>` +
               `first ${fmtTime(d.first_seen)}<br>last ${fmtTime(d.last_seen)}`;
      },
    },
    series: [{
      type: "graph",
      layout: "force",
      roam: true,
      draggable: true,
      categories,
      data: [...nodes.values()],
      links,
      // Long enough that labels do not collide, tight enough that a branch
      // still reads as one cluster.
      force: { repulsion: 320, edgeLength: [70, 160], gravity: 0.08, friction: 0.2 },
      emphasis: { focus: "adjacency", scale: 1.1, label: { fontWeight: "bold" } },
      label: { show: true, position: "right", color: fg, formatter: (p) => p.data.name },
      labelLayout: { hideOverlap: true },
      lineStyle: { color: "source", width: 1.5, curveness: 0.05, opacity: 0.8 },
      scaleLimit: { min: 0.4, max: 4 },
    }],
  }, true);
  state.graph.resize();

  state.graph.off("click");
  state.graph.on("click", (p) => {
    // Folders and namespaces are both places to browse to; the value is not.
    if (p.dataType === "node" && p.data.path) go(p.data.path);
  });
}

const escapeHtml = (text) =>
  String(text).replace(/[&<>"]/g, (c) =>
    ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);

/**
 * What the export will call this value: what its tags say, else what it looks
 * like. Kept in step with `infer_type` on the server, which is the one that
 * actually decides — this is only so the page can say what will happen.
 */
function stixTypeOf(item) {
  const tagged = tagValue(item.tags, "stix-type");
  if (tagged) return tagged;

  const value = (item.value || "").trim();
  if (value.includes("://")) return "url";
  if (/^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$/.test(value)) return "ipv4-addr";
  if (value.includes(":") && /^[0-9a-f:]+(\/\d{1,3})?$/i.test(value)) return "ipv6-addr";
  if (/^[^@\s]+@[^@\s]+$/.test(value)) return "email-addr";
  const hash = { 32: "file.MD5", 40: "file.SHA-1", 64: "file.SHA-256", 128: "file.SHA-512" };
  if (/^[0-9a-f]+$/i.test(value) && hash[value.length]) return hash[value.length];
  if (/^[^\s]+\.[a-z]{2,}$/i.test(value)) return "domain-name";
  return null;
}

/** The first `key:value` tag with this key. */
function tagValue(tags, key) {
  for (const tag of (tags || "").split(",")) {
    const at = tag.indexOf(":");
    if (at > 0 && tag.slice(0, at).trim().toLowerCase() === key) {
      return tag.slice(at + 1).trim();
    }
  }
  return null;
}

/** Replace the tags on the value being shown. */
async function saveTags() {
  if (!state.namespace || !state.value) return;
  $("d-save-tags").disabled = true;
  try {
    const item = await api("/_management/api/tags", "POST", {
      namespace: state.namespace,
      value: state.value,
      tags: $("d-tags").value,
    });
    setError("");
    // Redrawn so the observable type card agrees with the tags just saved.
    loadValue(item.value || state.value);
  } catch (e) {
    setError(e.message);
  } finally {
    $("d-save-tags").disabled = false;
  }
}

/**
 * Download the namespace as a STIX 2.1 bundle.
 *
 * The same `POST /_api/stix` an automation would call, so the button and a
 * script cannot drift apart. Fetched rather than linked because the export
 * needs the API key, which a plain link cannot carry.
 */
async function exportStix() {
  if (!state.namespace) {
    setError("Open a namespace first; the export is per namespace.");
    return;
  }
  const button = $("ns-export");
  button.disabled = true;
  try {
    const res = await fetch("/_api/stix", {
      method: "POST",
      headers: { Authorization: state.key, "Content-Type": "application/json" },
      body: JSON.stringify({ namespace: state.namespace }),
    });
    if (res.status === 401 || res.status === 403) {
      signOut("That key was not accepted.");
      return;
    }
    if (!res.ok) {
      const failure = await res.json().catch(() => ({}));
      throw new Error(failure.message || `${res.status} ${res.statusText}`);
    }

    const exported = res.headers.get("X-SightingDB-Exported");
    const skipped = Number(res.headers.get("X-SightingDB-Skipped") || 0);
    const truncated = res.headers.get("X-SightingDB-Truncated") === "true";

    const blob = new Blob([await res.text()], { type: "application/json" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = `${state.namespace.replace(/\//g, "-")}-stix.json`;
    link.click();
    URL.revokeObjectURL(link.href);

    // Anything the bundle could not carry is worth saying out loud rather than
    // leaving to be noticed in the file.
    const notes = [`Exported ${exported} value(s).`];
    if (skipped) {
      notes.push(`${skipped} skipped: no observable type, so no pattern  tag them with stix-type:`);
    }
    if (truncated) notes.push("the namespace holds more than one export can carry.");
    setError(notes.length > 1 ? notes.join(" ") : "");
  } catch (e) {
    setError(e.message);
  } finally {
    button.disabled = false;
  }
}

/**
 * The server buckets sightings by hour, so the histogram is those buckets
 * straight through. Empty hours between buckets are filled in, otherwise a
 * value seen in January and June would look like two adjacent bars.
 */
function drawHistogram(stats) {
  const buckets = Object.keys(stats).map(Number).sort((a, b) => a - b);
  $("d-nostats").textContent = buckets.length ? "" : "No statistics recorded for this value.";

  if (!state.chart) state.chart = echarts.init($("chart"), null, { renderer: "canvas" });
  if (!buckets.length) { state.chart.clear(); return; }

  const HOUR = 3600;
  const data = [];
  // Cap the gap filling: a value with a multi-year span would otherwise make
  // tens of thousands of empty points.
  const span = (buckets[buckets.length - 1] - buckets[0]) / HOUR;
  if (span <= 20000) {
    for (let t = buckets[0]; t <= buckets[buckets.length - 1]; t += HOUR) {
      data.push([t * 1000, stats[t] || 0]);
    }
  } else {
    for (const t of buckets) data.push([t * 1000, stats[t]]);
  }

  const dark = matchMedia("(prefers-color-scheme: dark)").matches;
  state.chart.setOption({
    backgroundColor: "transparent",
    textStyle: { color: dark ? "#e6e9ec" : "#1b1f24" },
    tooltip: {
      trigger: "axis",
      formatter: (p) => {
        const d = new Date(p[0].value[0]);
        return `${d.toISOString().replace("T", " ").replace(".000Z", "Z")}<br>` +
               `<b>${p[0].value[1]}</b> sighting(s) that hour`;
      },
    },
    grid: { left: 56, right: 20, top: 24, bottom: 64 },
    xAxis: { type: "time", axisLine: { lineStyle: { color: dark ? "#2b3138" : "#d9dee4" } } },
    yAxis: {
      type: "value", minInterval: 1, name: "sightings", nameGap: 34,
      nameLocation: "middle", splitLine: { lineStyle: { color: dark ? "#2b3138" : "#eceff2" } },
    },
    // Long histories are common, so shipping the zoom control is worthwhile.
    dataZoom: [{ type: "inside" }, { type: "slider", height: 22, bottom: 16 }],
    series: [{
      type: "bar", data, barMaxWidth: 24, large: true,
      itemStyle: { color: dark ? "#6f9dff" : "#0b5fff" },
    }],
  }, true);
  state.chart.resize();
}

addEventListener("resize", () => {
  if (state.chart) state.chart.resize();
  if (state.graph) state.graph.resize();
});

// --- keys ------------------------------------------------------------------

/** Grants arrive as two prefix lists; the editor works in rows instead. */
function grantRows(entry) {
  const byPrefix = new Map();
  for (const prefix of entry.read) byPrefix.set(prefix, { prefix, read: true, write: false });
  for (const prefix of entry.write) {
    const row = byPrefix.get(prefix) || { prefix, read: false, write: false };
    row.write = true;
    byPrefix.set(prefix, row);
  }
  return [...byPrefix.values()];
}

function chips(prefixes) {
  const span = document.createElement("span");
  if (!prefixes.length) {
    span.innerHTML = '<span class="chip none">—</span>';
    return span;
  }
  for (const prefix of prefixes) {
    const chip = document.createElement("span");
    chip.className = prefix === "" ? "chip all" : "chip";
    chip.textContent = prefix === "" ? "all namespaces" : prefix;
    span.append(chip);
  }
  return span;
}

async function loadKeys() {
  try {
    const keys = await api("/_management/api/keys");
    state.keys = keys;

    $("k-rows").replaceChildren(...keys.map((entry) => {
      const tr = document.createElement("tr");

      const key = document.createElement("td");
      key.className = "v";
      key.textContent = entry.key;

      const admin = document.createElement("td");
      admin.textContent = entry.admin ? "yes" : "";

      const read = document.createElement("td");
      read.append(chips(entry.read));
      const write = document.createElement("td");
      write.append(chips(entry.write));

      const actions = document.createElement("td");
      actions.className = "actions";
      const edit = document.createElement("button");
      edit.textContent = "Edit";
      edit.onclick = () => openKeyEditor(entry);
      const revoke = document.createElement("button");
      revoke.textContent = "Revoke";
      revoke.className = "danger";
      revoke.onclick = () => deleteKey(entry.key);
      actions.append(edit, revoke);

      tr.append(key, admin, read, write, actions);
      return tr;
    }));

    const admins = keys.filter((k) => k.admin).length;
    $("k-count").textContent =
      `${keys.length} key(s), ${admins} with management access`;
  } catch (e) { setError(e.message); }
}

function openKeyEditor(entry) {
  state.editing = entry ? entry.key : null;
  $("ke-title").textContent = entry ? `Edit ${entry.key}` : "New API key";
  $("ke-key").value = entry ? entry.key : "";
  // The name is the identity of the key; changing it would create a second one.
  $("ke-key").disabled = Boolean(entry);
  $("ke-generate").disabled = Boolean(entry);
  $("ke-admin").checked = entry ? entry.admin : false;
  $("ke-error").textContent = "";

  const rows = entry ? grantRows(entry) : [{ prefix: "", read: true, write: false }];
  $("ke-grants").replaceChildren();
  for (const row of rows) addGrantRow(row);

  $("key-editor").showModal();
}

function addGrantRow(row = { prefix: "", read: true, write: false }) {
  const div = document.createElement("div");
  div.className = "grant-row";

  const prefix = document.createElement("input");
  prefix.type = "text";
  prefix.placeholder = "namespace prefix (blank = all)";
  prefix.value = row.prefix;

  const mk = (text, checked) => {
    const label = document.createElement("label");
    const box = document.createElement("input");
    box.type = "checkbox";
    box.checked = checked;
    label.append(box, document.createTextNode(text));
    return [label, box];
  };
  const [readLabel, readBox] = mk("read", row.read);
  const [writeLabel, writeBox] = mk("write", row.write);

  const remove = document.createElement("button");
  remove.type = "button";
  remove.textContent = "×";
  remove.title = "Remove";
  remove.onclick = () => div.remove();

  div.append(prefix, readLabel, writeLabel, remove);
  div._read = () => ({ prefix: prefix.value.trim(), read: readBox.checked, write: writeBox.checked });
  $("ke-grants").append(div);
}

async function saveKey() {
  const rows = [...$("ke-grants").children].map((div) => div._read());
  const entry = {
    key: $("ke-key").value.trim(),
    admin: $("ke-admin").checked,
    read: rows.filter((r) => r.read).map((r) => r.prefix),
    write: rows.filter((r) => r.write).map((r) => r.prefix),
  };

  try {
    await api("/_management/api/keys", "POST", entry);
    $("key-editor").close();
    loadKeys();
  } catch (e) {
    // Kept open so the entry is not lost to a rejected name or a lockout guard.
    $("ke-error").textContent = e.message;
  }
}

async function deleteKey(key) {
  if (!confirm(`Revoke "${key}"? Anything using it stops working immediately.`)) return;
  try {
    await api(`/_management/api/keys/${encodeURIComponent(key)}`, "DELETE");
    loadKeys();
  } catch (e) { setError(e.message); }
}

// --- configuration ---------------------------------------------------------

async function showConfig() {
  setError("");
  try {
    const info = await api("/_management/api/info");
    const rows = [
      ["Version", info.version],
      ["Configuration file", info.config_path],
      ["Namespaces", info.namespaces],
      ["API keys", info.apikeys],
      ["API authentication", info.authenticate ? "on" : "off"],
      ["HTTP API", info.http_enabled ? "enabled" : "disabled"],
      ["Snapshot directory", info.dbdir || "not persisted"],
      ["Snapshot interval", info.snapshot_interval ? `${info.snapshot_interval}s` : "on shutdown only"],
      ["Sweep interval", info.sweep_interval ? `${info.sweep_interval}s` : "disabled"],
      ["Statistics retention", info.stats_retention ? `${info.stats_retention} buckets` : "unlimited"],
      ["Shadow TTL", info.shadow_ttl ? `${info.shadow_ttl}s` : "never expires"],
      ["DNS", info.dns ? `${info.dns.listen} for ${info.dns.zone}` : "disabled"],
      ["ZMQ ingest", info.zmq ? `${info.zmq.endpoint} (${info.zmq.format})` : "disabled"],
    ];
    if (info.dns) {
      for (const e of info.dns.exposed) {
        rows.push([`DNS ${e.label}.${info.dns.zone}`, `${e.namespace} (${e.encoding})`]);
      }
    }

    show("view-config");
    $("c-rows").replaceChildren(...rows.map(([k, v]) => {
      const tr = document.createElement("tr");
      const th = document.createElement("th");
      th.textContent = k;
      const td = document.createElement("td");
      td.className = "n";
      td.textContent = String(v);
      tr.append(th, td);
      return tr;
    }));
  } catch (e) { setError(e.message); }
}

// --- session ---------------------------------------------------------------

function signOut(message) {
  sessionStorage.removeItem("sightingdb.key");
  state.key = "";
  $("login-error").textContent = message || "";
  $("login").showModal();
}

async function start() {
  try {
    await api("/_management/api/session");
  } catch { return; }
  $("login").close();
  try {
    const info = await api("/_management/api/info");
    $("version").textContent = `v${info.version}`;
  } catch { /* the browser still works without the version */ }
  state.namespace = namespaceFromPath();
  render();
}

$("login-form").addEventListener("submit", async () => {
  state.key = $("key").value;
  sessionStorage.setItem("sightingdb.key", state.key);
  await start();
});

$("signout").onclick = () => signOut("");
$("nav-browse").onclick = () => render();
$("nav-keys").onclick = () => { setError(""); show("view-keys"); loadKeys(); };
$("nav-config").onclick = showConfig;
$("ns-up").onclick = () => go(parentOf(state.namespace));
$("ns-new").onclick = openNamespaceEditor;
$("ns-add").onclick = openValueEditor;
$("ns-export").onclick = exportStix;
$("d-save-tags").onclick = saveTags;
$("nn-cancel").onclick = () => $("ns-editor").close();
$("nn-name").addEventListener("input", previewNamespace);
$("ns-form").addEventListener("submit", (e) => { e.preventDefault(); createNamespace(); });
$("av-cancel").onclick = () => $("value-editor").close();
$("value-form").addEventListener("submit", (e) => { e.preventDefault(); addValues(); });
$("k-new").onclick = () => openKeyEditor(null);
$("ke-add").onclick = () => addGrantRow();
$("ke-cancel").onclick = () => $("key-editor").close();
$("key-form").addEventListener("submit", (e) => { e.preventDefault(); saveKey(); });
$("ke-generate").onclick = async () => {
  try {
    const { key } = await api("/_management/api/keys/generate");
    $("ke-key").value = key;
  } catch (e) { $("ke-error").textContent = e.message; }
};
$("d-back").onclick = () => render();
$("ns-prev").onclick = () => { state.nsOffset = Math.max(0, state.nsOffset - PAGE); loadListing(); };
$("ns-next").onclick = () => { state.nsOffset += PAGE; loadListing(); };
$("v-prev").onclick = () => { state.vOffset = Math.max(0, state.vOffset - PAGE); loadValues(); };
$("v-next").onclick = () => { state.vOffset += PAGE; loadValues(); };

let debounce;
const refilter = (fn, reset) => () => {
  clearTimeout(debounce);
  debounce = setTimeout(() => { reset(); fn(); }, 200);
};
$("ns-filter").addEventListener("input", refilter(loadListing, () => state.nsOffset = 0));
$("ns-deep").addEventListener("change", () => { state.nsOffset = 0; loadListing(); });
$("v-filter").addEventListener("input", refilter(loadValues, () => state.vOffset = 0));

if (state.key) { start(); } else { $("login").showModal(); }
</script>
</body>
</html>