hmcp-web 0.0.1 → 0.2.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.
Files changed (94) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +49 -2
  3. package/THIRD-PARTY-NOTICES.md +110 -0
  4. package/bin/hmcp-web.js +20 -0
  5. package/dist/api.d.ts +22 -0
  6. package/dist/api.js +1458 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +40 -0
  9. package/dist/contracts/onboarding.d.ts +233 -0
  10. package/dist/contracts/onboarding.js +1 -0
  11. package/dist/http.d.ts +72 -0
  12. package/dist/http.js +319 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.js +7 -0
  15. package/dist/model/app-servers.d.ts +85 -0
  16. package/dist/model/app-servers.js +109 -0
  17. package/dist/model/console-settings.d.ts +37 -0
  18. package/dist/model/console-settings.js +74 -0
  19. package/dist/model/doctor.d.ts +68 -0
  20. package/dist/model/doctor.js +254 -0
  21. package/dist/model/fs-browse.d.ts +9 -0
  22. package/dist/model/fs-browse.js +184 -0
  23. package/dist/model/gateway-config.d.ts +287 -0
  24. package/dist/model/gateway-config.js +760 -0
  25. package/dist/model/import-record.d.ts +80 -0
  26. package/dist/model/import-record.js +179 -0
  27. package/dist/model/metrics.d.ts +65 -0
  28. package/dist/model/metrics.js +213 -0
  29. package/dist/model/oauth-flows.d.ts +60 -0
  30. package/dist/model/oauth-flows.js +79 -0
  31. package/dist/model/pipeline.d.ts +58 -0
  32. package/dist/model/pipeline.js +84 -0
  33. package/dist/model/probe.d.ts +155 -0
  34. package/dist/model/probe.js +385 -0
  35. package/dist/model/process.d.ts +100 -0
  36. package/dist/model/process.js +278 -0
  37. package/dist/model/protection.d.ts +378 -0
  38. package/dist/model/protection.js +470 -0
  39. package/dist/model/registry-cache.d.ts +59 -0
  40. package/dist/model/registry-cache.js +238 -0
  41. package/dist/model/scan.d.ts +48 -0
  42. package/dist/model/scan.js +59 -0
  43. package/dist/model/server.d.ts +127 -0
  44. package/dist/model/server.js +243 -0
  45. package/dist/model/tools.d.ts +61 -0
  46. package/dist/model/tools.js +72 -0
  47. package/dist/routes/catalog.d.ts +8 -0
  48. package/dist/routes/catalog.js +47 -0
  49. package/dist/routes/connect-import.d.ts +9 -0
  50. package/dist/routes/connect-import.js +594 -0
  51. package/dist/routes/connect.d.ts +50 -0
  52. package/dist/routes/connect.js +691 -0
  53. package/dist/routes/github.d.ts +97 -0
  54. package/dist/routes/github.js +587 -0
  55. package/dist/routes/guard.d.ts +3 -0
  56. package/dist/routes/guard.js +166 -0
  57. package/dist/routes/oauth.d.ts +55 -0
  58. package/dist/routes/oauth.js +406 -0
  59. package/dist/routes/policy.d.ts +34 -0
  60. package/dist/routes/policy.js +513 -0
  61. package/dist/routes/runtime.d.ts +12 -0
  62. package/dist/routes/runtime.js +921 -0
  63. package/dist/routes/servers-add.d.ts +32 -0
  64. package/dist/routes/servers-add.js +1091 -0
  65. package/dist/routes/system.d.ts +4 -0
  66. package/dist/routes/system.js +13 -0
  67. package/dist/start.d.ts +56 -0
  68. package/dist/start.js +164 -0
  69. package/dist-ui/assets/Activity-CZ78RyRO.js +1 -0
  70. package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
  71. package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
  72. package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
  73. package/dist-ui/assets/Gallery-DB_OO7Vw.js +17 -0
  74. package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
  75. package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
  76. package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
  77. package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
  78. package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
  79. package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
  80. package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
  81. package/dist-ui/assets/index-DttDjRpu.js +16 -0
  82. package/dist-ui/assets/index-QeJyD5z2.css +2 -0
  83. package/dist-ui/assets/kit-DRVm92_t.js +4 -0
  84. package/dist-ui/brand/logo-256.png +0 -0
  85. package/dist-ui/brand/logo-512.png +0 -0
  86. package/dist-ui/brand/logo.svg +6 -0
  87. package/dist-ui/brand/mark.svg +5 -0
  88. package/dist-ui/fonts/OFL.txt +99 -0
  89. package/dist-ui/fonts/README.md +21 -0
  90. package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
  91. package/dist-ui/fonts/manrope-latin.woff2 +0 -0
  92. package/dist-ui/index.html +51 -0
  93. package/package.json +69 -6
  94. package/bin/notice.js +0 -7
@@ -0,0 +1,80 @@
1
+ import { z } from "zod";
2
+ import { type ScopeTarget, type Upstream } from "hmcp-gateway";
3
+ /**
4
+ * What one "Bring in servers" did, so its Undo can take back exactly that.
5
+ *
6
+ * Kept by the console, beside its list of toolboxes, rather than in the app's
7
+ * undo record: that record's shape is shared with `adopt --revert` and older
8
+ * builds, and is strict. The servers' own entries -- keys and all -- are in
9
+ * the app's undo record already (its `replaced` map); this file holds only
10
+ * names: which entry became which server, which locked keys the import made,
11
+ * and where each came from. Nothing in it is a secret, and it is still
12
+ * readable by its owner only, like everything else under `~/.hmcp`.
13
+ *
14
+ * One file per app settings location (`local` has one per project, inside
15
+ * the same `~/.claude.json`), named by a hash so no path from another
16
+ * program's file becomes a file name here.
17
+ */
18
+ export declare const ImportItemSchema: z.ZodObject<{
19
+ key: z.ZodString;
20
+ name: z.ZodString;
21
+ source: z.ZodEnum<{
22
+ config: "config";
23
+ extension: "extension";
24
+ }>;
25
+ upstream: z.ZodString;
26
+ added: z.ZodBoolean;
27
+ keys_created: z.ZodArray<z.ZodString>;
28
+ digest: z.ZodOptional<z.ZodString>;
29
+ back_in_app: z.ZodOptional<z.ZodBoolean>;
30
+ }, z.core.$strict>;
31
+ export type ImportItem = z.infer<typeof ImportItemSchema>;
32
+ export declare const ImportRecordSchema: z.ZodObject<{
33
+ version: z.ZodLiteral<1>;
34
+ scope: z.ZodString;
35
+ config_path: z.ZodString;
36
+ where: z.ZodOptional<z.ZodString>;
37
+ gateway_id: z.ZodString;
38
+ created_at: z.ZodString;
39
+ items: z.ZodArray<z.ZodObject<{
40
+ key: z.ZodString;
41
+ name: z.ZodString;
42
+ source: z.ZodEnum<{
43
+ config: "config";
44
+ extension: "extension";
45
+ }>;
46
+ upstream: z.ZodString;
47
+ added: z.ZodBoolean;
48
+ keys_created: z.ZodArray<z.ZodString>;
49
+ digest: z.ZodOptional<z.ZodString>;
50
+ back_in_app: z.ZodOptional<z.ZodBoolean>;
51
+ }, z.core.$strict>>;
52
+ }, z.core.$strict>;
53
+ export type ImportRecord = z.infer<typeof ImportRecordSchema>;
54
+ /**
55
+ * What a server runs, for "is it still the one the import added": program,
56
+ * arguments, folder and address. Never its settings or keys.
57
+ */
58
+ export declare function upstreamDigest(u: Upstream): string;
59
+ /** Where the record for this app settings location lives. */
60
+ export declare function importRecordPath(registryPath: string, target: ScopeTarget): string;
61
+ /** The record, or undefined when there is none or it can't be read (then there is nothing this can undo). */
62
+ export declare function readImportRecord(registryPath: string, target: ScopeTarget): ImportRecord | undefined;
63
+ /** Atomic and 0600, like the app's own undo record. */
64
+ export declare function writeImportRecord(registryPath: string, target: ScopeTarget, record: ImportRecord): void;
65
+ export declare function deleteImportRecord(registryPath: string, target: ScopeTarget): boolean;
66
+ /**
67
+ * The record as it still stands. The app's undo record is the truth about
68
+ * what was taken out of the app: `adopt --revert` at a terminal, or an older
69
+ * console, puts servers back without knowing this file exists.
70
+ *
71
+ * - The connection itself gone (no undo record, or one for another toolbox):
72
+ * the whole record goes. Undoing the connection said the servers brought
73
+ * in stay in the toolbox.
74
+ * - A server the app's record no longer holds is back in the app already.
75
+ * If the toolbox still has it as the import added it, it is kept, marked
76
+ * so: an Undo that put it back and then failed on the toolbox must still
77
+ * be able to take it out of the toolbox and delete its keys. Otherwise it
78
+ * is dropped.
79
+ */
80
+ export declare function readLiveImportRecord(registryPath: string, target: ScopeTarget): ImportRecord | undefined;
@@ -0,0 +1,179 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { canonicalJson, expandPath, readRegistry, sha256 } from "hmcp-core";
5
+ import { loadGatewayConfig, readBackup } from "hmcp-gateway";
6
+ /**
7
+ * What one "Bring in servers" did, so its Undo can take back exactly that.
8
+ *
9
+ * Kept by the console, beside its list of toolboxes, rather than in the app's
10
+ * undo record: that record's shape is shared with `adopt --revert` and older
11
+ * builds, and is strict. The servers' own entries -- keys and all -- are in
12
+ * the app's undo record already (its `replaced` map); this file holds only
13
+ * names: which entry became which server, which locked keys the import made,
14
+ * and where each came from. Nothing in it is a secret, and it is still
15
+ * readable by its owner only, like everything else under `~/.hmcp`.
16
+ *
17
+ * One file per app settings location (`local` has one per project, inside
18
+ * the same `~/.claude.json`), named by a hash so no path from another
19
+ * program's file becomes a file name here.
20
+ */
21
+ export const ImportItemSchema = z
22
+ .object({
23
+ /** The entry's name in the app, or the extension's id. */
24
+ key: z.string().min(1),
25
+ /** What a person knows it by. */
26
+ name: z.string().min(1),
27
+ source: z.enum(["config", "extension"]),
28
+ /** The server it is in the toolbox. */
29
+ upstream: z.string().min(1),
30
+ /** False when the toolbox already had it, and the import only took the app's copy out. */
31
+ added: z.boolean(),
32
+ /** Locked keys this import created for it (names only). */
33
+ keys_created: z.array(z.string()),
34
+ /**
35
+ * What the server ran as it was brought in (`upstreamDigest`), so Undo
36
+ * removes it only while it is still that server: one set up again by
37
+ * hand under the same name is the person's, and stays.
38
+ */
39
+ digest: z.string().optional(),
40
+ /**
41
+ * Already back in the app's settings -- an Undo put it back, then could
42
+ * not take it out of the toolbox -- so a later Undo only takes it out of
43
+ * the toolbox and deletes its keys.
44
+ */
45
+ back_in_app: z.boolean().optional()
46
+ })
47
+ .strict();
48
+ export const ImportRecordSchema = z
49
+ .object({
50
+ version: z.literal(1),
51
+ scope: z.string().min(1),
52
+ config_path: z.string().min(1),
53
+ /**
54
+ * Where in that file the servers were (`projects[<folder>].mcpServers`
55
+ * for Claude Code's `local`). Absent in a record from an earlier build of
56
+ * this branch; see `readImportRecord`.
57
+ */
58
+ where: z.string().min(1).optional(),
59
+ gateway_id: z.string().min(1),
60
+ created_at: z.string(),
61
+ items: z.array(ImportItemSchema)
62
+ })
63
+ .strict();
64
+ /**
65
+ * What a server runs, for "is it still the one the import added": program,
66
+ * arguments, folder and address. Never its settings or keys.
67
+ */
68
+ export function upstreamDigest(u) {
69
+ return sha256(canonicalJson(u.transport === "stdio" ? { t: "stdio", command: u.command, args: u.args, cwd: u.cwd ?? null } : { t: "http", url: u.url }));
70
+ }
71
+ /** Where the record for this app settings location lives. */
72
+ export function importRecordPath(registryPath, target) {
73
+ return join(dirname(registryPath), "imports", `${sha256(target.scope, target.path, target.where).slice(0, 32)}.json`);
74
+ }
75
+ /** The record, or undefined when there is none or it can't be read (then there is nothing this can undo). */
76
+ export function readImportRecord(registryPath, target) {
77
+ const path = importRecordPath(registryPath, target);
78
+ if (!existsSync(path))
79
+ return undefined;
80
+ try {
81
+ const parsed = ImportRecordSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
82
+ if (!parsed.success || parsed.data.scope !== target.scope)
83
+ return undefined;
84
+ /*
85
+ * A record without `where` is from an earlier build. Its file name is a
86
+ * hash of this very scope, file and place, so it was written for here:
87
+ * the place is filled in rather than the record ignored, which would
88
+ * leave its servers with no Undo.
89
+ */
90
+ if (parsed.data.where !== undefined && parsed.data.where !== target.where)
91
+ return undefined;
92
+ return { ...parsed.data, where: parsed.data.where ?? target.where };
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ /** Atomic and 0600, like the app's own undo record. */
99
+ export function writeImportRecord(registryPath, target, record) {
100
+ ImportRecordSchema.parse(record);
101
+ const path = importRecordPath(registryPath, target);
102
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
103
+ const tmp = join(dirname(path), `.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
104
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
105
+ try {
106
+ chmodSync(tmp, 0o600);
107
+ }
108
+ catch {
109
+ /* best effort: Windows has no such modes */
110
+ }
111
+ renameSync(tmp, path);
112
+ }
113
+ export function deleteImportRecord(registryPath, target) {
114
+ const path = importRecordPath(registryPath, target);
115
+ if (!existsSync(path))
116
+ return false;
117
+ unlinkSync(path);
118
+ return true;
119
+ }
120
+ /**
121
+ * The record as it still stands. The app's undo record is the truth about
122
+ * what was taken out of the app: `adopt --revert` at a terminal, or an older
123
+ * console, puts servers back without knowing this file exists.
124
+ *
125
+ * - The connection itself gone (no undo record, or one for another toolbox):
126
+ * the whole record goes. Undoing the connection said the servers brought
127
+ * in stay in the toolbox.
128
+ * - A server the app's record no longer holds is back in the app already.
129
+ * If the toolbox still has it as the import added it, it is kept, marked
130
+ * so: an Undo that put it back and then failed on the toolbox must still
131
+ * be able to take it out of the toolbox and delete its keys. Otherwise it
132
+ * is dropped.
133
+ */
134
+ export function readLiveImportRecord(registryPath, target) {
135
+ const rec = readImportRecord(registryPath, target);
136
+ if (!rec)
137
+ return undefined;
138
+ let backup;
139
+ try {
140
+ backup = readBackup(target);
141
+ }
142
+ catch {
143
+ // An unreadable record is not evidence that anything was given back.
144
+ return rec;
145
+ }
146
+ const held = backup && backup.scope === target.scope && backup.registry_id === rec.gateway_id ? backup.replaced : undefined;
147
+ const upstreams = held ? toolboxUpstreams(registryPath, rec.gateway_id) : undefined;
148
+ const items = held
149
+ ? rec.items.flatMap((i) => {
150
+ if (i.source !== "config" || Object.hasOwn(held, i.key))
151
+ return [i];
152
+ // A toolbox that can't be read is no evidence the server left it: kept.
153
+ const still = upstreams === undefined || upstreams.some((u) => u.name === i.upstream && (i.digest === undefined || upstreamDigest(u) === i.digest));
154
+ return i.added && still ? [{ ...i, back_in_app: true }] : [];
155
+ })
156
+ : [];
157
+ if (JSON.stringify(items) === JSON.stringify(rec.items))
158
+ return rec;
159
+ try {
160
+ if (items.length === 0)
161
+ deleteImportRecord(registryPath, target);
162
+ else
163
+ writeImportRecord(registryPath, target, { ...rec, items });
164
+ }
165
+ catch {
166
+ /* tidied next time; what is returned is already right */
167
+ }
168
+ return items.length === 0 ? undefined : { ...rec, items };
169
+ }
170
+ /** The toolbox's servers as its gateway.yaml has them now, or undefined when it can't be read. */
171
+ function toolboxUpstreams(registryPath, gatewayId) {
172
+ try {
173
+ const row = readRegistry(registryPath).servers.find((s) => s.id === gatewayId);
174
+ return row ? loadGatewayConfig(expandPath(row.config_path)).config.upstreams : undefined;
175
+ }
176
+ catch {
177
+ return undefined;
178
+ }
179
+ }
@@ -0,0 +1,65 @@
1
+ import { type DecisionKind } from "hmcp-core";
2
+ import type { LoadedServer } from "./server.js";
3
+ export type Window = "1h" | "24h" | "7d" | "30d" | "all";
4
+ export declare function isWindow(value: string): value is Window;
5
+ export interface Bucket {
6
+ /** Start of the bucket, epoch ms. */
7
+ readonly at: number;
8
+ readonly allow: number;
9
+ readonly approve: number;
10
+ readonly deny: number;
11
+ }
12
+ export interface ToolCount {
13
+ readonly tool: string;
14
+ readonly count: number;
15
+ }
16
+ export interface Coverage {
17
+ /** Records actually read and counted. */
18
+ readonly records: number;
19
+ /** Lines the backward scan touched, which is what the read cost. */
20
+ readonly scanned: number;
21
+ /** Lines that could not be parsed. Counted, never thrown on. */
22
+ readonly malformed: number;
23
+ /**
24
+ * True when the read reached the start of the window — so the counts are the
25
+ * window, and not merely its most recent `RECORD_BUDGET` records.
26
+ */
27
+ readonly complete: boolean;
28
+ readonly budget: number;
29
+ /** Epoch ms of the oldest and newest record counted, or null at an empty log. */
30
+ readonly oldest: number | null;
31
+ readonly newest: number | null;
32
+ }
33
+ export interface Metrics {
34
+ readonly window: Window;
35
+ readonly bucketMs: number;
36
+ readonly buckets: readonly Bucket[];
37
+ readonly decisions: Readonly<Record<DecisionKind, number>>;
38
+ /** Calls asking for a tool the toolbox doesn't have. Not in `decisions`: no rule refused them. */
39
+ readonly unknownTool: number;
40
+ readonly outcomes: Readonly<Record<string, number>>;
41
+ readonly effects: Readonly<Record<string, number>>;
42
+ /** Most-refused tools first. Refusals only — the question a reviewer asks. */
43
+ readonly refusedTools: readonly ToolCount[];
44
+ readonly busiestTools: readonly ToolCount[];
45
+ /** Milliseconds; null where too few records carried a duration to say. */
46
+ readonly duration: {
47
+ readonly p50: number;
48
+ readonly p95: number;
49
+ readonly samples: number;
50
+ } | null;
51
+ /** Ages in ms of what is waiting for a human right now, oldest first. */
52
+ readonly queue: readonly {
53
+ readonly id: string;
54
+ readonly tool: string;
55
+ readonly ageMs: number;
56
+ readonly expiresAt: number;
57
+ }[];
58
+ readonly coverage: Coverage;
59
+ readonly auditPath: string;
60
+ /** False when `audit.enabled` is off, in which case every count above is a zero that means nothing. */
61
+ readonly auditing: boolean;
62
+ }
63
+ export declare function buildMetrics(server: LoadedServer, tenant: string | null, window: Window,
64
+ /** Other toolboxes writing to the same log: their calls are not this one's (UT5 round 4). */
65
+ otherComponents?: readonly string[]): Metrics;
@@ -0,0 +1,213 @@
1
+ import { queryAuditLog } from "hmcp-core";
2
+ import { GUARD_LOOKALIKE_RULE, GUARD_OUTCOME_RULE } from "hmcp-gateway";
3
+ import { scopedFor, storeFor } from "./server.js";
4
+ /**
5
+ * Aggregates for the console's overview, read out of the audit log.
6
+ *
7
+ * Every number here is a count over a *bounded* read of an append-only file,
8
+ * and that bound is the whole problem. `queryAuditLog` caps one call at 1000
9
+ * records, so an aggregate has to page backwards itself, and a log longer than
10
+ * the budget means the answer describes a suffix of history rather than all of
11
+ * it. A chart that cannot say which of the two it is drawn from is worse than
12
+ * no chart: it reads as a total and is a sample.
13
+ *
14
+ * So the bound is part of the payload. `complete` says whether the window was
15
+ * read to its end, `scanned` and `records` say what it cost and covered, and
16
+ * `oldest`/`newest` say which stretch of time the counts actually describe. The
17
+ * UI is expected to render that, not to drop it.
18
+ */
19
+ /** How many records one metrics request will read before it stops. */
20
+ const RECORD_BUDGET = 5000;
21
+ /** One `queryAuditLog` call's own hard cap, mirrored here so paging matches it. */
22
+ const PAGE = 1000;
23
+ const WINDOW_MS = {
24
+ "1h": 3_600_000,
25
+ "24h": 86_400_000,
26
+ "7d": 604_800_000,
27
+ "30d": 2_592_000_000
28
+ };
29
+ export function isWindow(value) {
30
+ return value === "all" || value in WINDOW_MS;
31
+ }
32
+ /** The rule id the gateway records a call to a tool it doesn't have under. */
33
+ const UNKNOWN_TOOL_RULE = "gateway.unknown-tool";
34
+ /** One bucket per ~40 across the window, rounded to something a person reads. */
35
+ function bucketFor(window, spanMs) {
36
+ if (window === "1h")
37
+ return 60_000 * 2;
38
+ if (window === "24h")
39
+ return 3_600_000;
40
+ if (window === "7d")
41
+ return 3_600_000 * 6;
42
+ if (window === "30d")
43
+ return 86_400_000;
44
+ const target = Math.max(spanMs / 40, 60_000);
45
+ const steps = [60_000, 300_000, 3_600_000, 21_600_000, 86_400_000, 604_800_000];
46
+ return steps.find((s) => s >= target) ?? 604_800_000;
47
+ }
48
+ function percentile(sorted, p) {
49
+ if (sorted.length === 0)
50
+ return 0;
51
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
52
+ return sorted[idx];
53
+ }
54
+ function topN(counts, n) {
55
+ return [...counts.entries()]
56
+ .sort((a, b) => (b[1] === a[1] ? a[0].localeCompare(b[0]) : b[1] - a[1]))
57
+ .slice(0, n)
58
+ .map(([tool, count]) => ({ tool, count }));
59
+ }
60
+ /**
61
+ * Reads backwards from the end of the log until the window is covered or the
62
+ * budget is spent, whichever comes first.
63
+ *
64
+ * Paging rather than one big call because `queryAuditLog` caps a single read at
65
+ * 1000 records; asking for more silently gets 1000 and would make `complete`
66
+ * a lie.
67
+ */
68
+ function collect(path, tenant, since, exclude) {
69
+ const records = [];
70
+ let scanned = 0;
71
+ let malformed = 0;
72
+ let cursor;
73
+ let complete = false;
74
+ while (records.length < RECORD_BUDGET) {
75
+ const page = queryAuditLog(path, {
76
+ limit: Math.min(PAGE, RECORD_BUDGET - records.length),
77
+ ...(cursor !== undefined ? { beforeSeq: cursor } : {}),
78
+ ...(since !== undefined ? { since } : {}),
79
+ ...(exclude.length > 0 ? { excludeComponent: exclude } : {}),
80
+ // A null tenant means "every tenant" — the cross-tenant overview a
81
+ // single-tenant deployment wants. A named one, including the empty
82
+ // string, is one customer's rows and nobody else's.
83
+ ...(tenant !== null ? { tenant: [tenant] } : {})
84
+ });
85
+ records.push(...page.records);
86
+ scanned += page.scanned;
87
+ malformed += page.malformed;
88
+ if (page.nextCursor === null) {
89
+ complete = true;
90
+ break;
91
+ }
92
+ cursor = page.nextCursor;
93
+ }
94
+ return { records, scanned, malformed, complete };
95
+ }
96
+ export function buildMetrics(server, tenant, window,
97
+ /** Other toolboxes writing to the same log: their calls are not this one's (UT5 round 4). */
98
+ otherComponents = []) {
99
+ const now = Date.now();
100
+ const since = window === "all" ? undefined : new Date(now - WINDOW_MS[window]).toISOString();
101
+ const auditing = server.policy.audit.enabled;
102
+ const read = collect(server.auditPath, tenant, since, otherComponents);
103
+ const decisions = { allow: 0, approve: 0, deny: 0 };
104
+ const outcomes = {};
105
+ const effects = {};
106
+ const refused = new Map();
107
+ const busiest = new Map();
108
+ const durations = [];
109
+ let unknownTool = 0;
110
+ const bucketed = new Map();
111
+ let oldest = null;
112
+ let newest = null;
113
+ const spanMs = window === "all" ? now - (Date.parse(read.records.at(-1)?.ts ?? "") || now) : WINDOW_MS[window];
114
+ const bucketMs = bucketFor(window, spanMs);
115
+ for (const record of read.records) {
116
+ // Only what an AI app asked for. The console writes its own actions to the
117
+ // same log -- turning protection on, adding a server -- under component
118
+ // "hmcp-web" or a "(policy)"/"(gateway)" tool, and counting those made
119
+ // Home say "Allowed 7, Blocked 1" before any AI had run.
120
+ if (record.component === "hmcp-web" || /^\(.*\)$/.test(record.tool ?? ""))
121
+ continue;
122
+ const at = Date.parse(record.ts);
123
+ if (!Number.isFinite(at))
124
+ continue;
125
+ if (oldest === null || at < oldest)
126
+ oldest = at;
127
+ if (newest === null || at > newest)
128
+ newest = at;
129
+ /*
130
+ * A call to a tool the toolbox doesn't have was refused because there is
131
+ * nothing to run, not by a rule: counted on its own, so "Blocked" (and,
132
+ * in watch-only mode, "would have been blocked") means what protection
133
+ * did (UT5 round 4).
134
+ */
135
+ if (record.rule_id === UNKNOWN_TOOL_RULE) {
136
+ unknownTool++;
137
+ continue;
138
+ }
139
+ /*
140
+ * A call the Claude Code guard checked is written twice: the decision
141
+ * before it ran (outcome "relayed") and what became of it after ("guard.
142
+ * outcome"). Counted once: the decision, effect, tool and time from the
143
+ * first, and how it ended from the second. A name the guard declined to
144
+ * treat as the toolbox's own is a note beside the call, not a call.
145
+ */
146
+ if (record.rule_id === GUARD_LOOKALIKE_RULE)
147
+ continue;
148
+ if (record.rule_id === GUARD_OUTCOME_RULE) {
149
+ outcomes[record.outcome] = (outcomes[record.outcome] ?? 0) + 1;
150
+ continue;
151
+ }
152
+ const decision = record.decision;
153
+ if (decision === "allow" || decision === "approve" || decision === "deny")
154
+ decisions[decision]++;
155
+ if (record.outcome !== "relayed")
156
+ outcomes[record.outcome] = (outcomes[record.outcome] ?? 0) + 1;
157
+ // An unclassified call is its own fact, not a missing one — the whole
158
+ // reason `on_unclassified: deny` exists — so it is counted under its own
159
+ // key rather than dropped.
160
+ effects[record.effect ?? "unclassified"] = (effects[record.effect ?? "unclassified"] ?? 0) + 1;
161
+ if (record.tool) {
162
+ busiest.set(record.tool, (busiest.get(record.tool) ?? 0) + 1);
163
+ if (decision === "deny")
164
+ refused.set(record.tool, (refused.get(record.tool) ?? 0) + 1);
165
+ }
166
+ if (typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)) {
167
+ durations.push(record.duration_ms);
168
+ }
169
+ const slot = Math.floor(at / bucketMs) * bucketMs;
170
+ const cell = bucketed.get(slot) ?? { allow: 0, approve: 0, deny: 0 };
171
+ if (decision === "allow" || decision === "approve" || decision === "deny")
172
+ cell[decision]++;
173
+ bucketed.set(slot, cell);
174
+ }
175
+ durations.sort((a, b) => a - b);
176
+ // `null` tenant means every tenant, so the queue has to come from the
177
+ // unscoped list — a scoped read with the empty tenant would silently show
178
+ // one tenant's queue under a heading that claims to cover all of them.
179
+ const pending = tenant === null ? storeFor(server).listPendingAll(50) : scopedFor(server, tenant).listPending(50);
180
+ const queue = pending
181
+ .map((row) => ({ id: row.id, tool: row.tool, ageMs: now - row.created_at, expiresAt: row.expires_at }))
182
+ .sort((a, b) => b.ageMs - a.ageMs);
183
+ return {
184
+ window,
185
+ bucketMs,
186
+ buckets: [...bucketed.entries()]
187
+ .sort((a, b) => a[0] - b[0])
188
+ .map(([at, cell]) => ({ at, ...cell })),
189
+ decisions,
190
+ unknownTool,
191
+ outcomes,
192
+ effects,
193
+ refusedTools: topN(refused, 8),
194
+ busiestTools: topN(busiest, 8),
195
+ // Fewer than five samples is not a percentile, it is two numbers with a
196
+ // label on them. Null so the UI shows nothing rather than something false.
197
+ duration: durations.length >= 5
198
+ ? { p50: percentile(durations, 50), p95: percentile(durations, 95), samples: durations.length }
199
+ : null,
200
+ queue,
201
+ coverage: {
202
+ records: read.records.length,
203
+ scanned: read.scanned,
204
+ malformed: read.malformed,
205
+ complete: read.complete,
206
+ budget: RECORD_BUDGET,
207
+ oldest,
208
+ newest
209
+ },
210
+ auditPath: server.auditPath,
211
+ auditing
212
+ };
213
+ }
@@ -0,0 +1,60 @@
1
+ import type { OAuthClientRegistration } from "hmcp-core";
2
+ import { type Discovered } from "hmcp-gateway";
3
+ /**
4
+ * Sign-ins in progress, held in this console process's memory only.
5
+ *
6
+ * A flow carries the PKCE verifier, which together with the code is enough to
7
+ * get a token, so it is never written to disk and never sent to the browser.
8
+ * The browser holds only the `state`: 32 random bytes that name the flow.
9
+ *
10
+ * Single use: the first `/complete` for a state takes the verifier out and
11
+ * nothing can complete it again. A flow that is not finished within ten
12
+ * minutes is expired, then forgotten.
13
+ */
14
+ export declare const FLOW_TTL_MS: number;
15
+ export type FlowStatus = "waiting" | "completing" | "done" | "failed" | "expired";
16
+ export interface OAuthFlow {
17
+ readonly state: string;
18
+ readonly secretName: string;
19
+ readonly label?: string;
20
+ codeVerifier: string;
21
+ readonly redirectUri: string;
22
+ readonly discovered: Discovered;
23
+ readonly client: OAuthClientRegistration;
24
+ readonly serverUrl: string;
25
+ /** Plain name of the provider, for messages: "Notion". */
26
+ readonly provider: string;
27
+ status: FlowStatus;
28
+ problem?: string;
29
+ readonly expiresAt: number;
30
+ }
31
+ export type FlowInit = Omit<OAuthFlow, "state" | "status" | "expiresAt" | "problem">;
32
+ export type TakeResult = {
33
+ ok: true;
34
+ flow: OAuthFlow;
35
+ } | {
36
+ ok: false;
37
+ why: "unknown" | "expired" | "used";
38
+ flow?: OAuthFlow;
39
+ };
40
+ export declare class OAuthFlows {
41
+ private readonly opts;
42
+ private readonly flows;
43
+ constructor(opts?: {
44
+ ttlMs?: number;
45
+ now?: () => number;
46
+ });
47
+ private now;
48
+ create(init: FlowInit): OAuthFlow;
49
+ /** For status polling. A waiting flow past its time reads as expired. */
50
+ get(state: string): OAuthFlow | undefined;
51
+ /**
52
+ * Claims a waiting flow for completion. After this the flow cannot be
53
+ * claimed again, whatever the outcome.
54
+ */
55
+ take(state: string): TakeResult;
56
+ finish(flow: OAuthFlow, problem?: string): void;
57
+ /** Drops flows long past their expiry; an expired flow loses its verifier at once. */
58
+ sweep(): void;
59
+ get size(): number;
60
+ }
@@ -0,0 +1,79 @@
1
+ import { newState } from "hmcp-gateway";
2
+ /**
3
+ * Sign-ins in progress, held in this console process's memory only.
4
+ *
5
+ * A flow carries the PKCE verifier, which together with the code is enough to
6
+ * get a token, so it is never written to disk and never sent to the browser.
7
+ * The browser holds only the `state`: 32 random bytes that name the flow.
8
+ *
9
+ * Single use: the first `/complete` for a state takes the verifier out and
10
+ * nothing can complete it again. A flow that is not finished within ten
11
+ * minutes is expired, then forgotten.
12
+ */
13
+ export const FLOW_TTL_MS = 10 * 60 * 1000;
14
+ /** How long a finished or expired flow can still be asked about. */
15
+ const KEEP_AFTER_MS = 10 * 60 * 1000;
16
+ export class OAuthFlows {
17
+ opts;
18
+ flows = new Map();
19
+ constructor(opts = {}) {
20
+ this.opts = opts;
21
+ }
22
+ now() {
23
+ return (this.opts.now ?? Date.now)();
24
+ }
25
+ create(init) {
26
+ this.sweep();
27
+ const flow = { ...init, state: newState(), status: "waiting", expiresAt: this.now() + (this.opts.ttlMs ?? FLOW_TTL_MS) };
28
+ this.flows.set(flow.state, flow);
29
+ return flow;
30
+ }
31
+ /** For status polling. A waiting flow past its time reads as expired. */
32
+ get(state) {
33
+ this.sweep();
34
+ return this.flows.get(state);
35
+ }
36
+ /**
37
+ * Claims a waiting flow for completion. After this the flow cannot be
38
+ * claimed again, whatever the outcome.
39
+ */
40
+ take(state) {
41
+ this.sweep();
42
+ const flow = this.flows.get(state);
43
+ if (!flow)
44
+ return { ok: false, why: "unknown" };
45
+ if (flow.status === "expired")
46
+ return { ok: false, why: "expired", flow };
47
+ if (flow.status !== "waiting")
48
+ return { ok: false, why: "used", flow };
49
+ if (this.now() > flow.expiresAt) {
50
+ flow.codeVerifier = "";
51
+ flow.status = "expired";
52
+ return { ok: false, why: "expired", flow };
53
+ }
54
+ flow.status = "completing";
55
+ return { ok: true, flow };
56
+ }
57
+ finish(flow, problem) {
58
+ flow.codeVerifier = "";
59
+ flow.status = problem ? "failed" : "done";
60
+ if (problem)
61
+ flow.problem = problem;
62
+ }
63
+ /** Drops flows long past their expiry; an expired flow loses its verifier at once. */
64
+ sweep() {
65
+ const now = this.now();
66
+ for (const [state, flow] of this.flows) {
67
+ if (now > flow.expiresAt) {
68
+ flow.codeVerifier = "";
69
+ if (flow.status === "waiting")
70
+ flow.status = "expired";
71
+ }
72
+ if (now > flow.expiresAt + KEEP_AFTER_MS)
73
+ this.flows.delete(state);
74
+ }
75
+ }
76
+ get size() {
77
+ return this.flows.size;
78
+ }
79
+ }