hmcp-core 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 (76) hide show
  1. package/README.md +19 -3
  2. package/dist/approvals.d.ts +508 -0
  3. package/dist/approvals.js +1445 -0
  4. package/dist/argpath.d.ts +75 -0
  5. package/dist/argpath.js +189 -0
  6. package/dist/audit.d.ts +297 -0
  7. package/dist/audit.js +524 -0
  8. package/dist/canonical.d.ts +78 -0
  9. package/dist/canonical.js +146 -0
  10. package/dist/classify-held.d.ts +47 -0
  11. package/dist/classify-held.js +60 -0
  12. package/dist/classify-name.d.ts +55 -0
  13. package/dist/classify-name.js +255 -0
  14. package/dist/decide.d.ts +168 -0
  15. package/dist/decide.js +518 -0
  16. package/dist/egress.d.ts +123 -0
  17. package/dist/egress.js +544 -0
  18. package/dist/enforce.d.ts +78 -0
  19. package/dist/enforce.js +231 -0
  20. package/dist/exposure-apply.d.ts +51 -0
  21. package/dist/exposure-apply.js +69 -0
  22. package/dist/exposure.d.ts +81 -0
  23. package/dist/exposure.js +65 -0
  24. package/dist/file-lock.d.ts +70 -0
  25. package/dist/file-lock.js +165 -0
  26. package/dist/glob.d.ts +11 -0
  27. package/dist/glob.js +55 -0
  28. package/dist/grants.d.ts +204 -0
  29. package/dist/grants.js +372 -0
  30. package/dist/http-util.d.ts +52 -0
  31. package/dist/http-util.js +81 -0
  32. package/dist/index.d.ts +35 -0
  33. package/dist/index.js +36 -0
  34. package/dist/inventory.d.ts +100 -0
  35. package/dist/inventory.js +88 -0
  36. package/dist/ip.d.ts +15 -0
  37. package/dist/ip.js +186 -0
  38. package/dist/jwt.d.ts +57 -0
  39. package/dist/jwt.js +199 -0
  40. package/dist/live-state.d.ts +76 -0
  41. package/dist/live-state.js +57 -0
  42. package/dist/migrate.d.ts +22 -0
  43. package/dist/migrate.js +318 -0
  44. package/dist/pins.d.ts +119 -0
  45. package/dist/pins.js +125 -0
  46. package/dist/policy-batch.d.ts +89 -0
  47. package/dist/policy-batch.js +340 -0
  48. package/dist/policy-source.d.ts +161 -0
  49. package/dist/policy-source.js +299 -0
  50. package/dist/policy-write.d.ts +627 -0
  51. package/dist/policy-write.js +1697 -0
  52. package/dist/policy.d.ts +456 -0
  53. package/dist/policy.js +448 -0
  54. package/dist/redact.d.ts +65 -0
  55. package/dist/redact.js +191 -0
  56. package/dist/registry.d.ts +41 -0
  57. package/dist/registry.js +121 -0
  58. package/dist/remember-defaults.d.ts +9 -0
  59. package/dist/remember-defaults.js +9 -0
  60. package/dist/remember.d.ts +91 -0
  61. package/dist/remember.js +386 -0
  62. package/dist/resolve.d.ts +22 -0
  63. package/dist/resolve.js +34 -0
  64. package/dist/runtime-state.d.ts +65 -0
  65. package/dist/runtime-state.js +35 -0
  66. package/dist/secrets.d.ts +159 -0
  67. package/dist/secrets.js +361 -0
  68. package/dist/tenant.d.ts +83 -0
  69. package/dist/tenant.js +182 -0
  70. package/dist/unicode.d.ts +40 -0
  71. package/dist/unicode.js +103 -0
  72. package/dist/within-host.d.ts +33 -0
  73. package/dist/within-host.js +91 -0
  74. package/dist/within-real.d.ts +7 -0
  75. package/dist/within-real.js +28 -0
  76. package/package.json +33 -4
package/dist/grants.js ADDED
@@ -0,0 +1,372 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { globMatch } from "./glob.js";
4
+ import { formatPath, leafPaths, parseArgPath, resolveArgPath } from "./argpath.js";
5
+ import { checkArgConstraints } from "./decide.js";
6
+ import { ArgConstraintSchema, EffectSchema } from "./policy.js";
7
+ /**
8
+ * Standing grants: a pre-approval for a *class* of call rather than one exact
9
+ * call.
10
+ *
11
+ * An ordinary approval is bound to `sha256(tool + canonical arguments)`, which
12
+ * is what stops a grant for a 10-unit transfer releasing a 10,000-unit one. A
13
+ * standing grant deliberately gives that up in exchange for not asking a human
14
+ * the same question repeatedly, so every other bound is kept tight:
15
+ *
16
+ * - it matches a glob over the tool name, not "anything";
17
+ * - its argument constraints are the same `ArgConstraint` vocabulary policy
18
+ * rules use, checked by the same `checkArgConstraints`;
19
+ * - it always expires, because a pre-approval with no end date is a posture
20
+ * change and those belong in `policy.yaml` where they get reviewed;
21
+ * - it can cap how many calls it releases;
22
+ * - it is revocable, and creation, use and revocation are all audited.
23
+ *
24
+ * A grant is strictly weaker than editing the policy: it cannot widen what
25
+ * `decide()` permits, only spare a human from re-approving what policy already
26
+ * routed to them.
27
+ */
28
+ /**
29
+ * The longest a pre-approval may last. A grant is a concession made without a
30
+ * human in the loop at call time, so it has to come back for renewal; past a
31
+ * month it is a posture change wearing a grant's clothes.
32
+ */
33
+ export const MAX_GRANT_TTL_SECONDS = 30 * 24 * 60 * 60;
34
+ export const GRANTS_SCHEMA = `
35
+ CREATE TABLE IF NOT EXISTS standing_grants (
36
+ id TEXT PRIMARY KEY,
37
+ component TEXT NOT NULL DEFAULT '',
38
+ tenant TEXT NOT NULL DEFAULT '',
39
+ created_at INTEGER NOT NULL,
40
+ expires_at INTEGER NOT NULL,
41
+ tool_match TEXT NOT NULL,
42
+ effect TEXT,
43
+ constraints TEXT NOT NULL,
44
+ max_uses INTEGER,
45
+ uses INTEGER NOT NULL DEFAULT 0,
46
+ reason TEXT NOT NULL,
47
+ created_by TEXT NOT NULL,
48
+ state TEXT NOT NULL,
49
+ revoked_at INTEGER,
50
+ revoked_by TEXT,
51
+ closed INTEGER NOT NULL DEFAULT 0
52
+ );
53
+ CREATE INDEX IF NOT EXISTS grants_active ON standing_grants (component, tenant, state, expires_at);
54
+ `;
55
+ export function newGrantId() {
56
+ return `sg_${randomBytes(6).toString("hex")}`;
57
+ }
58
+ /**
59
+ * Validates a grant as it arrives from an untrusted surface such as the web
60
+ * console. `expires_at` is required and must be in the future; a grant that is
61
+ * already expired would be silently useless rather than refused.
62
+ */
63
+ export const StandingGrantDraftSchema = z
64
+ .object({
65
+ tool_match: z.string().min(1),
66
+ effect: EffectSchema.nullish(),
67
+ constraints: z.record(z.string(), ArgConstraintSchema).default({}),
68
+ expires_at: z.number().int().positive(),
69
+ max_uses: z.number().int().positive().nullish(),
70
+ reason: z.string().min(1),
71
+ created_by: z.string().min(1),
72
+ closed: z.boolean().optional()
73
+ })
74
+ .strict();
75
+ /**
76
+ * True when a constraint states a limit on the value itself.
77
+ *
78
+ * Told apart from `narrows` below because the two answer different questions
79
+ * and `required: true` answers only one of them. It narrows what a grant
80
+ * covers, since a call that leaves the argument out is no longer matched. It
81
+ * is not a limit on the value: it is the difference between "amount must be
82
+ * sent" and "amount may be up to 3,000", and only the second is the grant's
83
+ * author saying how far past a rule's bound they meant to go.
84
+ */
85
+ function boundsValue(c) {
86
+ return (c.max !== undefined ||
87
+ c.min !== undefined ||
88
+ c.enum !== undefined ||
89
+ c.pattern !== undefined ||
90
+ c.maxLength !== undefined ||
91
+ c.maxItems !== undefined ||
92
+ c.sum_max !== undefined ||
93
+ c.count_max !== undefined ||
94
+ c.const !== undefined ||
95
+ c.same_items !== undefined ||
96
+ c.within !== undefined ||
97
+ c.host !== undefined);
98
+ }
99
+ /** True when a constraint narrows which calls a grant covers at all. */
100
+ function narrows(c) {
101
+ return boundsValue(c) || c.required === true;
102
+ }
103
+ export function parseGrantDraft(raw, now = Date.now()) {
104
+ const draft = StandingGrantDraftSchema.parse(raw);
105
+ if (draft.expires_at <= now) {
106
+ throw new Error("expires_at is in the past; a grant must be able to release at least one call");
107
+ }
108
+ if (draft.expires_at - now > MAX_GRANT_TTL_SECONDS * 1000) {
109
+ throw new Error(`a grant may not last longer than ${MAX_GRANT_TTL_SECONDS / 86400} days; ` +
110
+ "a longer-lived permission belongs in policy.yaml where it gets reviewed");
111
+ }
112
+ // An unparseable pattern would be a closed door rather than an open one, but
113
+ // it is still a typo worth reporting at creation instead of at call time.
114
+ if (draft.tool_match.includes("{") && !draft.tool_match.includes("}")) {
115
+ throw new Error(`tool_match "${draft.tool_match}" has an unclosed brace`);
116
+ }
117
+ // Each constraint key is an argument path. One that cannot be parsed would
118
+ // never match anything, and a grant whose bounds match nothing is an
119
+ // unbounded grant wearing a bound — so it is refused at creation, where
120
+ // someone is around to fix the typo, rather than at call time.
121
+ for (const [spec, c] of Object.entries(draft.constraints ?? {})) {
122
+ const parsed = parseArgPath(spec);
123
+ if (!parsed.ok) {
124
+ throw new Error(`constraint "${spec}" is not a usable argument path: ${parsed.error}`);
125
+ }
126
+ if (c.pattern !== undefined) {
127
+ try {
128
+ new RegExp(c.pattern);
129
+ }
130
+ catch {
131
+ throw new Error(`constraint "${spec}" has an invalid regular expression: ${c.pattern}`);
132
+ }
133
+ }
134
+ }
135
+ // A wildcard grant bounded only by time is indistinguishable from widening
136
+ // the policy, which is the one thing the console must not do quietly. Require
137
+ // a second bound so its blast radius is something a reviewer can state.
138
+ // `{a,b}` is a list of tools, which is a family as surely as `a*` is.
139
+ const wildcard = /[*?{]/.test(draft.tool_match);
140
+ // A constraint that only says a value may be absent bounds nothing, so it
141
+ // does not count as the second bound a wildcard grant needs.
142
+ const constrained = Object.values(draft.constraints ?? {}).some(narrows);
143
+ if (wildcard && !constrained && (draft.max_uses ?? null) === null) {
144
+ throw new Error(`tool_match "${draft.tool_match}" matches a family of tools, so it also needs max_uses ` +
145
+ "or argument constraints; an unbounded wildcard grant is equivalent to editing policy.yaml");
146
+ }
147
+ return draft;
148
+ }
149
+ /** Decodes the stored constraint JSON, treating corruption as "no match". */
150
+ export function grantConstraints(row) {
151
+ try {
152
+ const parsed = JSON.parse(row.constraints);
153
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
154
+ return null;
155
+ return parsed;
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ }
161
+ /**
162
+ * Whether this grant covers this call.
163
+ *
164
+ * A grant whose constraints reject the arguments is *not a match*, which means
165
+ * the caller falls through to ordinary approval. It must never turn into a
166
+ * denial: a narrow pre-approval exists to save a human some clicks, and letting
167
+ * it block a call the human would have waved through would make adding one
168
+ * actively harmful.
169
+ */
170
+ /**
171
+ * Whether a grant can apply to this tool at all, before any call's arguments
172
+ * are weighed.
173
+ *
174
+ * Split out for a reader with no call in front of them -- a preview of a grant
175
+ * that does not exist yet. Asking `grantMatches` instead means handing it an
176
+ * empty call, and an empty call breaks every value bound the grant has ("x is
177
+ * bounded by policy but absent"), so the more carefully a grant was written
178
+ * the less it would appear to cover. What its bounds then do to a real call is
179
+ * a separate question, and `grantBoundGaps` is the honest half of it.
180
+ */
181
+ export function grantCoversTool(row, tool, effect) {
182
+ if (!globMatch(row.tool_match, tool)) {
183
+ return { matches: false, reason: `tool "${tool}" does not match "${row.tool_match}"` };
184
+ }
185
+ if (row.effect !== null && row.effect !== effect) {
186
+ return { matches: false, reason: `grant covers ${row.effect} calls, this one is ${effect ?? "unclassified"}` };
187
+ }
188
+ return { matches: true, reason: `covered by standing grant ${row.id}` };
189
+ }
190
+ /**
191
+ * The arguments a call sends that a closed grant names nowhere: `force: true`
192
+ * added to an approved push, a new key inside an approved object (R2 N4), or
193
+ * a new key inside one item of an approved list (`items[0].price`, R2 round
194
+ * 3). Every place a value sits must be named by a bound written for exactly
195
+ * that place: a bound on a list (`items: { maxItems: 1 }`) says how long it
196
+ * may be, not what its items may hold. A value that sends "nothing" -- null,
197
+ * an empty list or object -- is still sent: the server receives it.
198
+ */
199
+ export function addedArgs(args, constraints) {
200
+ const named = [];
201
+ // A list pinned whole (`same_items`) names everything inside it: its items are compared whole, keys and all.
202
+ const whole = [];
203
+ for (const [spec, c] of Object.entries(constraints)) {
204
+ const parsed = parseArgPath(spec);
205
+ if (!parsed.ok)
206
+ continue;
207
+ for (const match of resolveArgPath(args, parsed.segments)) {
208
+ named.push([...match.path]);
209
+ if (c.same_items !== undefined)
210
+ whole.push([...match.path]);
211
+ }
212
+ }
213
+ const same = (a, b) => a.length === b.length && a.every((seg, i) => seg === b[i]);
214
+ const under = (leaf, list) => leaf.length >= list.length && list.every((seg, i) => seg === leaf[i]);
215
+ return leafPaths(args)
216
+ .filter((leaf) => !named.some((path) => same(leaf.path, path)) && !whole.some((path) => under(leaf.path, path)))
217
+ .map((leaf) => formatPath(leaf.path));
218
+ }
219
+ /**
220
+ * A grant "don't ask again" made before list items were pinned whole (R2
221
+ * round 4, R4-1). It bounded each field of a list's items on its own
222
+ * (`transfers[].to`, `transfers[].amount`), so approved items could be
223
+ * re-paired, repeated or swapped: approving 5 to alice and 1 to bob released
224
+ * 5 to bob. A remembered grant with a bound inside a list that is not pinned
225
+ * whole releases nothing now; the next call asks, and can be remembered again.
226
+ */
227
+ export function hasLooseListItems(row) {
228
+ if (!/^remembered while approving\b/.test(row.reason))
229
+ return false;
230
+ let constraints;
231
+ try {
232
+ constraints = JSON.parse(row.constraints);
233
+ }
234
+ catch {
235
+ return false;
236
+ }
237
+ if (constraints === null || typeof constraints !== "object")
238
+ return false;
239
+ return Object.keys(constraints).some((spec) => {
240
+ const at = spec.indexOf("[]");
241
+ if (at < 0)
242
+ return false;
243
+ const list = spec.slice(0, at);
244
+ return constraints[list]?.same_items === undefined;
245
+ });
246
+ }
247
+ /**
248
+ * A grant "don't ask again" made in an older build, which wrote it open. It is
249
+ * now read as covering only the arguments it names -- with none named, only a
250
+ * call with no arguments -- so it is shown as needing a fresh approval rather
251
+ * than as covering "any arguments" (R3 round 3).
252
+ */
253
+ export function isOlderRemembered(row) {
254
+ return !row.closed && /^remembered while approving\b/.test(row.reason);
255
+ }
256
+ /** True when a key named `__proto__` sits anywhere in the arguments (it can't be compared safely). */
257
+ export function hasProtoKey(value) {
258
+ if (Array.isArray(value))
259
+ return value.some(hasProtoKey);
260
+ if (value !== null && typeof value === "object") {
261
+ return Object.keys(value).some((k) => k === "__proto__" || hasProtoKey(value[k]));
262
+ }
263
+ return false;
264
+ }
265
+ export function grantMatches(row, tool, effect, args) {
266
+ const covers = grantCoversTool(row, tool, effect);
267
+ if (!covers.matches)
268
+ return covers;
269
+ const constraints = grantConstraints(row);
270
+ if (constraints === null) {
271
+ return { matches: false, reason: "the grant's stored constraints are unreadable" };
272
+ }
273
+ if (hasProtoKey(args)) {
274
+ return { matches: false, reason: "this call sends an argument named __proto__, so no pre-approval releases it" };
275
+ }
276
+ if (hasLooseListItems(row)) {
277
+ return {
278
+ matches: false,
279
+ reason: "this pre-approval was made by an older version, which did not keep the items of a list together, so it is asked about again"
280
+ };
281
+ }
282
+ const violations = checkArgConstraints(args, constraints);
283
+ if (violations.length > 0) {
284
+ return {
285
+ matches: false,
286
+ reason: violations.map((v) => `${v.arg}: ${v.message}`).join("; ")
287
+ };
288
+ }
289
+ /*
290
+ * A grant remembered from one approval by an older build was written open:
291
+ * it covered any arguments, or any argument it didn't name. It is read the
292
+ * way "Approve and don't ask again" is meant now, so a call that goes past
293
+ * what was approved is asked about again rather than released (R3 NEW-3).
294
+ */
295
+ if (row.closed || isOlderRemembered(row)) {
296
+ const added = addedArgs(args, constraints);
297
+ if (added.length > 0) {
298
+ return {
299
+ matches: false,
300
+ reason: `this call sends ${added.join(", ")}, which the approved call did not, so it is asked about again`
301
+ };
302
+ }
303
+ }
304
+ return { matches: true, reason: `covered by standing grant ${row.id}` };
305
+ }
306
+ /**
307
+ * Whether a grant's own constraints bound every one of the given arguments.
308
+ *
309
+ * `held` is the list of arguments that broke a rule's bound: concrete paths
310
+ * such as `transfer.amount` or `items[3].qty`, or the bound's own path
311
+ * (`amount`) when the argument was absent. An argument is bounded by the grant
312
+ * when one of its constraints says something about a value -- presence alone
313
+ * does not count -- and either is written against that exact path, or resolves
314
+ * in this call to that argument or to a container it sits inside.
315
+ *
316
+ * "Says something about a value" is `boundsValue`, so a constraint that only
317
+ * requires the argument to be sent does not make the grant its author's
318
+ * statement of how far past the rule a call may go.
319
+ */
320
+ export function grantBoundsArgs(row, args, held) {
321
+ const constraints = grantConstraints(row);
322
+ if (constraints === null)
323
+ return false;
324
+ const bounded = [];
325
+ for (const [spec, c] of Object.entries(constraints)) {
326
+ if (!boundsValue(c))
327
+ continue;
328
+ bounded.push(spec);
329
+ const parsed = parseArgPath(spec);
330
+ if (!parsed.ok)
331
+ continue;
332
+ for (const match of resolveArgPath(args, parsed.segments))
333
+ bounded.push(formatPath(match.path));
334
+ }
335
+ return held.every((arg) => bounded.some((path) => arg === path || arg.startsWith(`${path}.`) || arg.startsWith(`${path}[`)));
336
+ }
337
+ /**
338
+ * Which of a rule's bounds a grant would not release a call for.
339
+ *
340
+ * `grantBoundsArgs` answers this for one call, from the arguments it actually
341
+ * sent. A reviewer about to create a grant has no call in front of them, so
342
+ * this answers the same question from the two sets of bounds alone: a rule
343
+ * bound that the grant says nothing about is one that will still stop a call
344
+ * and still ask a person, however well the grant matches the tool.
345
+ *
346
+ * Without it a preview reads "covers: yes" for a tool whose every interesting
347
+ * call the grant will not release -- a preview that promises what enforcement
348
+ * then refuses, which is worse than no preview.
349
+ *
350
+ * Both sides are patterns (`items[].qty`), compared as `grantBoundsArgs`
351
+ * compares a resolved path: the same spec, or a container the rule's bound
352
+ * sits inside.
353
+ */
354
+ export function grantBoundGaps(grantConstraints, ruleArgs) {
355
+ const ruleBounded = Object.entries(ruleArgs ?? {})
356
+ .filter(([, c]) => boundsValue(c))
357
+ .map(([spec]) => spec);
358
+ if (ruleBounded.length === 0)
359
+ return [];
360
+ const granted = Object.entries(grantConstraints ?? {})
361
+ .filter(([, c]) => boundsValue(c))
362
+ .map(([spec]) => spec);
363
+ return ruleBounded.filter((spec) => !granted.some((g) => spec === g || spec.startsWith(`${g}.`) || spec.startsWith(`${g}[`)));
364
+ }
365
+ /** True when the grant can still release a call, ignoring argument matching. */
366
+ export function grantIsLive(row, now = Date.now()) {
367
+ if (row.state !== "active")
368
+ return false;
369
+ if (row.expires_at <= now)
370
+ return false;
371
+ return row.max_uses === null || row.uses < row.max_uses;
372
+ }
@@ -0,0 +1,52 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ /**
3
+ * HTTP primitives shared by every surface in this project that speaks HTTP.
4
+ *
5
+ * These began life in the review console and moved here when the gateway grew
6
+ * an HTTP transport of its own. The gateway cannot import the console — that
7
+ * is the wrong direction through the package graph — and a second copy of an
8
+ * error type is how two surfaces come to disagree about what a 422 means.
9
+ *
10
+ * What is deliberately *not* here is the console's request pipeline: the
11
+ * loopback-only gate, the "a mutating request must carry an Origin header"
12
+ * rule, and the session-cookie plus double-submit CSRF check. Those are right
13
+ * for a privileged browser surface on a developer's machine and wrong for an
14
+ * MCP endpoint — an MCP client is not a browser, sends no Origin, carries no
15
+ * cookie, and every one of its calls is a POST. Shared code that three of four
16
+ * callers must disable is not shared code.
17
+ */
18
+ /**
19
+ * The cap on a request body this project will buffer.
20
+ *
21
+ * Sized for configuration and tool arguments, which is what every body here
22
+ * actually is. A caller that needs to move bulk data is doing something this
23
+ * layer is not for.
24
+ */
25
+ export declare const MAX_BODY_BYTES: number;
26
+ export declare class HttpError extends Error {
27
+ readonly status: number;
28
+ readonly code: string;
29
+ readonly detail?: unknown | undefined;
30
+ constructor(status: number, code: string, message: string, detail?: unknown | undefined);
31
+ }
32
+ export declare const badRequest: (m: string, d?: unknown) => HttpError;
33
+ export declare const notFound: (m: string) => HttpError;
34
+ export declare const conflict: (m: string) => HttpError;
35
+ export declare const unprocessable: (m: string, d?: unknown) => HttpError;
36
+ /**
37
+ * Reads a JSON request body, refusing one that is too large.
38
+ *
39
+ * The cap is checked as the body arrives rather than afterwards, so an
40
+ * oversized request is abandoned part-way instead of being buffered in full
41
+ * and then rejected.
42
+ */
43
+ export declare function readBody(req: IncomingMessage): Promise<unknown>;
44
+ /**
45
+ * Compares two secrets without leaking their contents through timing.
46
+ *
47
+ * The length check short-circuits, so this reveals whether two values are the
48
+ * same length. That is accepted: every secret compared here is a fixed-width
49
+ * generated token, so the length carries nothing an attacker does not already
50
+ * know from the format.
51
+ */
52
+ export declare function constantTimeEquals(a: string, b: string): boolean;
@@ -0,0 +1,81 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ /**
3
+ * HTTP primitives shared by every surface in this project that speaks HTTP.
4
+ *
5
+ * These began life in the review console and moved here when the gateway grew
6
+ * an HTTP transport of its own. The gateway cannot import the console — that
7
+ * is the wrong direction through the package graph — and a second copy of an
8
+ * error type is how two surfaces come to disagree about what a 422 means.
9
+ *
10
+ * What is deliberately *not* here is the console's request pipeline: the
11
+ * loopback-only gate, the "a mutating request must carry an Origin header"
12
+ * rule, and the session-cookie plus double-submit CSRF check. Those are right
13
+ * for a privileged browser surface on a developer's machine and wrong for an
14
+ * MCP endpoint — an MCP client is not a browser, sends no Origin, carries no
15
+ * cookie, and every one of its calls is a POST. Shared code that three of four
16
+ * callers must disable is not shared code.
17
+ */
18
+ /**
19
+ * The cap on a request body this project will buffer.
20
+ *
21
+ * Sized for configuration and tool arguments, which is what every body here
22
+ * actually is. A caller that needs to move bulk data is doing something this
23
+ * layer is not for.
24
+ */
25
+ export const MAX_BODY_BYTES = 256 * 1024;
26
+ export class HttpError extends Error {
27
+ status;
28
+ code;
29
+ detail;
30
+ constructor(status, code, message, detail) {
31
+ super(message);
32
+ this.status = status;
33
+ this.code = code;
34
+ this.detail = detail;
35
+ this.name = "HttpError";
36
+ }
37
+ }
38
+ export const badRequest = (m, d) => new HttpError(400, "bad-request", m, d);
39
+ export const notFound = (m) => new HttpError(404, "not-found", m);
40
+ export const conflict = (m) => new HttpError(409, "conflict", m);
41
+ export const unprocessable = (m, d) => new HttpError(422, "unprocessable", m, d);
42
+ /**
43
+ * Reads a JSON request body, refusing one that is too large.
44
+ *
45
+ * The cap is checked as the body arrives rather than afterwards, so an
46
+ * oversized request is abandoned part-way instead of being buffered in full
47
+ * and then rejected.
48
+ */
49
+ export async function readBody(req) {
50
+ const chunks = [];
51
+ let size = 0;
52
+ for await (const chunk of req) {
53
+ size += chunk.length;
54
+ if (size > MAX_BODY_BYTES)
55
+ throw badRequest(`request body exceeds ${MAX_BODY_BYTES} bytes`);
56
+ chunks.push(chunk);
57
+ }
58
+ if (size === 0)
59
+ return undefined;
60
+ try {
61
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
62
+ }
63
+ catch {
64
+ throw badRequest("request body is not valid JSON");
65
+ }
66
+ }
67
+ /**
68
+ * Compares two secrets without leaking their contents through timing.
69
+ *
70
+ * The length check short-circuits, so this reveals whether two values are the
71
+ * same length. That is accepted: every secret compared here is a fixed-width
72
+ * generated token, so the length carries nothing an attacker does not already
73
+ * know from the format.
74
+ */
75
+ export function constantTimeEquals(a, b) {
76
+ const left = Buffer.from(a);
77
+ const right = Buffer.from(b);
78
+ if (left.length !== right.length)
79
+ return false;
80
+ return timingSafeEqual(left, right);
81
+ }
@@ -0,0 +1,35 @@
1
+ export * from "./canonical.js";
2
+ export * from "./unicode.js";
3
+ export * from "./http-util.js";
4
+ export * from "./migrate.js";
5
+ export * from "./jwt.js";
6
+ export * from "./glob.js";
7
+ export * from "./argpath.js";
8
+ export * from "./policy.js";
9
+ export * from "./policy-source.js";
10
+ export * from "./classify-name.js";
11
+ export * from "./policy-write.js";
12
+ export * from "./policy-batch.js";
13
+ export * from "./classify-held.js";
14
+ export * from "./redact.js";
15
+ export * from "./decide.js";
16
+ export * from "./enforce.js";
17
+ export * from "./grants.js";
18
+ export * from "./within-host.js";
19
+ export * from "./within-real.js";
20
+ export * from "./remember.js";
21
+ export * from "./exposure.js";
22
+ export * from "./exposure-apply.js";
23
+ export * from "./inventory.js";
24
+ export * from "./pins.js";
25
+ export * from "./runtime-state.js";
26
+ export * from "./resolve.js";
27
+ export * from "./registry.js";
28
+ export * from "./audit.js";
29
+ export * from "./approvals.js";
30
+ export * from "./egress.js";
31
+ export * from "./ip.js";
32
+ export * from "./tenant.js";
33
+ export * from "./file-lock.js";
34
+ export * from "./secrets.js";
35
+ export * from "./live-state.js";
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ export * from "./canonical.js";
2
+ export * from "./unicode.js";
3
+ export * from "./http-util.js";
4
+ export * from "./migrate.js";
5
+ export * from "./jwt.js";
6
+ export * from "./glob.js";
7
+ export * from "./argpath.js";
8
+ export * from "./policy.js";
9
+ export * from "./policy-source.js";
10
+ export * from "./classify-name.js";
11
+ export * from "./policy-write.js";
12
+ export * from "./policy-batch.js";
13
+ export * from "./classify-held.js";
14
+ export * from "./redact.js";
15
+ export * from "./decide.js";
16
+ export * from "./enforce.js";
17
+ export * from "./grants.js";
18
+ export * from "./within-host.js";
19
+ // Installs the real-path resolver the `within` bound compares with (Node only).
20
+ export * from "./within-real.js";
21
+ export * from "./remember.js";
22
+ export * from "./exposure.js";
23
+ export * from "./exposure-apply.js";
24
+ export * from "./inventory.js";
25
+ export * from "./pins.js";
26
+ export * from "./runtime-state.js";
27
+ export * from "./resolve.js";
28
+ export * from "./registry.js";
29
+ export * from "./audit.js";
30
+ export * from "./approvals.js";
31
+ export * from "./egress.js";
32
+ export * from "./ip.js";
33
+ export * from "./tenant.js";
34
+ export * from "./file-lock.js";
35
+ export * from "./secrets.js";
36
+ export * from "./live-state.js";
@@ -0,0 +1,100 @@
1
+ import type { Effect } from "./policy.js";
2
+ import type { ToolExposureRow } from "./exposure.js";
3
+ /**
4
+ * What a running gateway is actually serving, published so other processes can
5
+ * read it.
6
+ *
7
+ * A gateway's tool surface does not exist on disk. It comes from each upstream's
8
+ * MCP `tools/list` — the same call, and the same three fields, the agent itself
9
+ * sees — and only the gateway process has made that call. So a console has two
10
+ * ways to learn a gateway's tools: speak MCP to every upstream itself, which
11
+ * means spawning child processes and opening sockets on a page load, or read
12
+ * what the gateway already knows. This is the second.
13
+ *
14
+ * Keyed by `component` and not by tenant, deliberately, for the same reason
15
+ * `runtime_state` is: the base tool set is a property of the process. Every
16
+ * tenant of one gateway is offered the identical set, and `tools/list` narrows
17
+ * it per caller only by the process-wide `hidden` flag and that tenant's
18
+ * `tool_exposure` rows. Inventory is what the upstreams offer; exposure is what
19
+ * a tenant may use. Joining the two is `toolSurface`.
20
+ *
21
+ * `pid` is carried because `runtime_state` upserts by component on a
22
+ * last-to-start-wins basis. That is tolerable for a policy digest and not for a
23
+ * tool list: two gateways sharing a config name but pointing at different
24
+ * upstreams — a dev and a staging process on one box, both on the default
25
+ * `store_path` — would otherwise overwrite each other's rows and a reader would
26
+ * see a surface no single process serves. A reader compares this against the
27
+ * live `runtime_state` row and ignores rows from any other process.
28
+ */
29
+ export interface ToolInventoryRow {
30
+ readonly component: string;
31
+ readonly tool: string;
32
+ readonly pid: number;
33
+ /** The upstream server this tool came from, as named in the gateway config. */
34
+ readonly upstream: string;
35
+ /** Null when the gateway could not classify it; such a tool is refused. */
36
+ readonly effect: Effect | null;
37
+ readonly effect_source: string;
38
+ /** The description as advertised to the model, after any rewriting. */
39
+ readonly description: string;
40
+ /** The upstream's own text, before rewriting, so the two can be compared. */
41
+ readonly raw_description: string;
42
+ /** The `inputSchema` the model is advertised, as JSON: the upstream's, less any annotation `on_injection` removed. */
43
+ readonly input_schema: string;
44
+ /** 1 when gateway policy hides it from every tenant. */
45
+ readonly hidden: number;
46
+ /** JSON array of injection pattern ids found in the upstream's text. */
47
+ readonly injection: string | null;
48
+ readonly discovered_at: number;
49
+ }
50
+ export declare const TOOL_INVENTORY_SCHEMA = "\nCREATE TABLE IF NOT EXISTS tool_inventory (\n component TEXT NOT NULL,\n tool TEXT NOT NULL,\n pid INTEGER NOT NULL,\n upstream TEXT NOT NULL,\n effect TEXT,\n effect_source TEXT NOT NULL,\n description TEXT NOT NULL,\n raw_description TEXT NOT NULL,\n input_schema TEXT NOT NULL,\n hidden INTEGER NOT NULL,\n injection TEXT,\n discovered_at INTEGER NOT NULL,\n PRIMARY KEY (component, tool)\n);\n";
51
+ /** What a gateway hands the store, before the store stamps it. */
52
+ export interface ToolInventoryInput {
53
+ readonly tool: string;
54
+ readonly upstream: string;
55
+ readonly effect: Effect | null;
56
+ readonly effectSource: string;
57
+ readonly description: string;
58
+ readonly rawDescription: string;
59
+ readonly inputSchema: unknown;
60
+ readonly hidden: boolean;
61
+ readonly injection: readonly string[] | null;
62
+ }
63
+ /**
64
+ * One tool as a reader should see it: what the gateway is serving, narrowed by
65
+ * what this tenant may use.
66
+ */
67
+ export interface ToolSurfaceEntry {
68
+ readonly name: string;
69
+ readonly upstream: string;
70
+ readonly effect: Effect | null;
71
+ readonly effectSource: string;
72
+ /** What the model is told. */
73
+ readonly description: string;
74
+ /** What the upstream said, which differs when injection was rewritten. */
75
+ readonly rawDescription: string;
76
+ readonly inputSchema: unknown;
77
+ /**
78
+ * Hidden from every tenant by gateway policy — `on_injection: deny`. Distinct
79
+ * from `disabled`, which is one tenant's switch and is reversible by them.
80
+ */
81
+ readonly hiddenByPolicy: boolean;
82
+ readonly injection: readonly string[] | null;
83
+ readonly disabled: {
84
+ readonly reason: string;
85
+ readonly setAt: number;
86
+ readonly setBy: string;
87
+ } | null;
88
+ }
89
+ /**
90
+ * Joins a tool surface against one tenant's exposure rows.
91
+ *
92
+ * The single implementation of "what is this tenant's tool surface", so a
93
+ * gateway answering for itself from memory and a console reading what that
94
+ * gateway published cannot answer the same question two different ways. The
95
+ * two differ only in where the tools came from, which is why both entry points
96
+ * below funnel into this one.
97
+ */
98
+ export declare function toolSurfaceOf(tools: readonly ToolInventoryInput[], disabled: readonly ToolExposureRow[]): ToolSurfaceEntry[];
99
+ /** The same join, for a reader that has the published rows rather than a gateway. */
100
+ export declare function toolSurface(inventory: readonly ToolInventoryRow[], disabled: readonly ToolExposureRow[]): ToolSurfaceEntry[];