hmcp-core 0.0.1 → 0.1.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 +289 -0
  7. package/dist/audit.js +512 -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 +371 -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
@@ -0,0 +1,78 @@
1
+ import type { ApprovalBroker } from "./approvals.js";
2
+ import type { AuditLog } from "./audit.js";
3
+ import type { Decision } from "./decide.js";
4
+ import type { Effect, Policy } from "./policy.js";
5
+ /**
6
+ * The enforcement pipeline the gateway runs every upstream call through:
7
+ * classify, decide, obtain approval if the decision calls for it, run the call,
8
+ * and record the outcome either way. Both halves of this project call it so the
9
+ * two cannot drift apart.
10
+ */
11
+ export interface CallResult {
12
+ readonly ok: boolean;
13
+ /** Text handed back to the agent. */
14
+ readonly message: string;
15
+ readonly decision: Decision;
16
+ readonly approvalId: string | null;
17
+ readonly upstream?: {
18
+ host: string | null;
19
+ method: string | null;
20
+ path: string | null;
21
+ status: number | null;
22
+ bytes: number | null;
23
+ } | null;
24
+ }
25
+ export interface EnforceOptions {
26
+ readonly policy: Policy;
27
+ readonly audit: AuditLog;
28
+ readonly approvals: ApprovalBroker;
29
+ readonly tenantValue?: string | undefined;
30
+ readonly actor?: string;
31
+ readonly session?: string;
32
+ }
33
+ export interface EnforceCall<T> {
34
+ readonly tool: string;
35
+ readonly effect: Effect | undefined;
36
+ readonly args: Record<string, unknown>;
37
+ /**
38
+ * Set when an exposure override has switched this tool off. Resolved by the
39
+ * caller, which is the half that knows the server's identity and owns the
40
+ * approvals database handle.
41
+ */
42
+ readonly disabled?: {
43
+ readonly reason: string;
44
+ } | undefined;
45
+ /** Shown to a human in the approval prompt. */
46
+ readonly target?: string;
47
+ /** Runs only after the decision permits it. */
48
+ readonly run: () => Promise<{
49
+ result: T;
50
+ upstream?: CallResult["upstream"];
51
+ }>;
52
+ }
53
+ export type EnforceOutcome<T> = {
54
+ readonly kind: "ok";
55
+ readonly result: T;
56
+ readonly decision: Decision;
57
+ readonly approvalId: string | null;
58
+ } | {
59
+ readonly kind: "refused";
60
+ readonly message: string;
61
+ readonly decision: Decision;
62
+ /** Set when the call was not refused but parked for a person to approve. */
63
+ readonly pending?: {
64
+ readonly approvalId: string;
65
+ readonly isNew: boolean;
66
+ };
67
+ };
68
+ /**
69
+ * Runs one tool call under policy. `run` is invoked only on a permitting
70
+ * decision; a refusal never reaches it, so there is no path where the upstream
71
+ * is touched before the decision is made.
72
+ */
73
+ export declare function enforceCall<T>(options: EnforceOptions, call: EnforceCall<T>): Promise<EnforceOutcome<T>>;
74
+ /**
75
+ * The text of a tool result that reports its own failure, or null for one
76
+ * that does not. Cut short: it is a pointer for a person, not a transcript.
77
+ */
78
+ export declare function toolErrorText(result: unknown): string | null;
@@ -0,0 +1,231 @@
1
+ import { policyDigest } from "./runtime-state.js";
2
+ import { decide } from "./decide.js";
3
+ import { EgressDenied } from "./egress.js";
4
+ import { EXPOSURE_RULE } from "./exposure.js";
5
+ /**
6
+ * Runs one tool call under policy. `run` is invoked only on a permitting
7
+ * decision; a refusal never reaches it, so there is no path where the upstream
8
+ * is touched before the decision is made.
9
+ */
10
+ export async function enforceCall(options, call) {
11
+ const { policy, audit, approvals } = options;
12
+ const started = Date.now();
13
+ const { args_hash, args_redacted } = audit.prepareArgs(call.args);
14
+ const base = {
15
+ tool: call.tool,
16
+ args_hash,
17
+ args_redacted,
18
+ tenant: options.tenantValue ?? null,
19
+ actor: options.actor,
20
+ session: options.session
21
+ };
22
+ const decision = decide({
23
+ tool: call.tool,
24
+ effect: call.effect,
25
+ args: call.args,
26
+ policy,
27
+ tenant: policy.tenant ? { expected: options.tenantValue } : undefined,
28
+ ...(call.disabled ? { disabled: true, disabledReason: call.disabled.reason } : {})
29
+ });
30
+ let approvalId = null;
31
+ let grantId = null;
32
+ /*
33
+ * Observe mode: the decision above is recorded and not applied. The call
34
+ * runs whatever it says, nobody is asked, and no approval or grant is spent
35
+ * on it.
36
+ *
37
+ * One decision is still applied. A tool an operator has switched off is an
38
+ * explicit act by a person, usually in a hurry, and "it was only observing"
39
+ * is not something they should have to remember at that moment. So the kill
40
+ * switch works in both modes, and its refusal is recorded as the real
41
+ * refusal it is.
42
+ */
43
+ const observing = policy.enforcement === "observe" && decision.ruleId !== EXPOSURE_RULE;
44
+ const mark = observing ? { observe: true } : {};
45
+ if (!observing && decision.kind === "deny") {
46
+ audit.append({
47
+ ...base,
48
+ effect: decision.effect,
49
+ decision: "deny",
50
+ rule_id: decision.ruleId,
51
+ reason: decision.reason,
52
+ outcome: "denied",
53
+ duration_ms: Date.now() - started
54
+ });
55
+ return {
56
+ kind: "refused",
57
+ decision,
58
+ // `agentReason` where the decision drew a line between what the record
59
+ // should say and what the caller should be told; `reason` otherwise.
60
+ message: `Refused by policy (${decision.ruleId}): ${decision.agentReason ?? decision.reason}. ` +
61
+ `The person's protection settings block this, so it cannot be approved; trying again will not help. ` +
62
+ `Tell them it was blocked.`
63
+ };
64
+ }
65
+ if (!observing && decision.kind === "approve") {
66
+ const outcome = await approvals.request({
67
+ tool: call.tool,
68
+ effect: decision.effect,
69
+ args: call.args,
70
+ reason: decision.reason,
71
+ actor: options.actor ?? "agent",
72
+ session: options.session ?? "unknown",
73
+ target: call.target,
74
+ ruleId: decision.ruleId,
75
+ // Recorded on the row so an auditor reading a past grant can say which
76
+ // bounds it was judged against, not only what the bounds are now.
77
+ policyDigest: policyDigest(policy),
78
+ ...(decision.violations ? { violations: decision.violations } : {}),
79
+ ...(decision.heldArgs ? { heldArgs: decision.heldArgs } : {})
80
+ });
81
+ if (!outcome.granted) {
82
+ audit.append({
83
+ ...base,
84
+ effect: decision.effect,
85
+ decision: "approve",
86
+ rule_id: decision.ruleId,
87
+ /*
88
+ * Both halves: what policy decided, and what became of the approval.
89
+ * For a call held by an argument bound the first half is the only
90
+ * place the log says *which* bound was exceeded, and a log that
91
+ * records a hold without recording why is the half of this feature
92
+ * nobody can audit. Values under a redacted key are already
93
+ * `<redacted>` by the time they reach here.
94
+ */
95
+ reason: decision.violations?.length
96
+ ? `${outcome.reason} — ${decision.reason}`
97
+ : outcome.reason,
98
+ outcome: outcome.refusedByPerson ? "denied" : "pending-approval",
99
+ approval_id: outcome.approvalId,
100
+ duration_ms: Date.now() - started
101
+ });
102
+ const message = [
103
+ outcome.refusedByPerson
104
+ ? `Refused by the person: ${outcome.reason}`
105
+ : `Approval required (${decision.ruleId}): ${outcome.reason}`,
106
+ outcome.instructions
107
+ ]
108
+ .filter(Boolean)
109
+ .join("\n\n");
110
+ return {
111
+ kind: "refused",
112
+ decision,
113
+ message,
114
+ ...(outcome.parked && outcome.approvalId
115
+ ? { pending: { approvalId: outcome.approvalId, isNew: outcome.parked === "new" } }
116
+ : {})
117
+ };
118
+ }
119
+ approvalId = outcome.approvalId;
120
+ grantId = outcome.via === "standing" ? (outcome.grantId ?? null) : null;
121
+ if (grantId) {
122
+ // Recorded before the call runs, and separately from the call's own
123
+ // record, so that spending a pre-approval is auditable even if the
124
+ // upstream request then fails. This is the "every pre-approval is in the
125
+ // log" guarantee for the use half; create and revoke are written by
126
+ // whoever manages the grant.
127
+ audit.append({
128
+ ...base,
129
+ effect: decision.effect,
130
+ decision: "approve",
131
+ rule_id: "standing_grant.use",
132
+ reason: `released by standing grant ${grantId} without asking a human: ${decision.reason}`,
133
+ outcome: "completed",
134
+ approval_id: approvalId,
135
+ grant_id: grantId,
136
+ duration_ms: Date.now() - started
137
+ });
138
+ }
139
+ }
140
+ /*
141
+ * The call is permitted. Before it touches the upstream, check that the
142
+ * record of it can be written: once the upstream has acted there is no
143
+ * taking it back, and a call that ran with nothing written down is the one
144
+ * outcome an audit log exists to rule out. Refusals above never pass
145
+ * through here, so a broken log cannot be used to switch enforcement off.
146
+ */
147
+ if (policy.audit.enabled && policy.audit.on_failure === "refuse") {
148
+ try {
149
+ audit.assertWritable();
150
+ }
151
+ catch (err) {
152
+ const why = err.message;
153
+ process.stderr.write(`[hmcp] refusing ${call.tool}: the audit log at ${audit.path} cannot be written: ${why}\n`);
154
+ return {
155
+ kind: "refused",
156
+ decision,
157
+ message: `Refused: this call was permitted, but the audit log cannot be written (${why}) and policy ` +
158
+ `(audit.on_failure: refuse) does not let a call run unrecorded. This is a fault in the gateway's ` +
159
+ `own storage, not in the request; whoever runs the gateway needs to fix it.`
160
+ };
161
+ }
162
+ }
163
+ try {
164
+ const { result, upstream } = await call.run();
165
+ /*
166
+ * An MCP tool reports its own failure in the result (`isError: true`),
167
+ * not by throwing: a key the service refused, a file it could not write.
168
+ * Recorded as completed, that call read as fine everywhere -- Activity,
169
+ * Home, "nothing needs a look" -- while every use of the tool failed.
170
+ */
171
+ const toolError = toolErrorText(result);
172
+ audit.append({
173
+ ...base,
174
+ ...mark,
175
+ effect: decision.effect,
176
+ decision: decision.kind,
177
+ rule_id: decision.ruleId,
178
+ reason: decision.reason,
179
+ outcome: toolError === null ? "completed" : "error",
180
+ ...(toolError === null ? {} : { error: audit.prepareText(toolError, call.args) }),
181
+ approval_id: approvalId,
182
+ grant_id: grantId,
183
+ upstream: upstream ?? null,
184
+ duration_ms: Date.now() - started
185
+ });
186
+ return { kind: "ok", result, decision, approvalId };
187
+ }
188
+ catch (err) {
189
+ // Written by the upstream, so it is untrusted text on its way to disk: a
190
+ // validation error that quotes the value it rejected would otherwise put
191
+ // back the secret `args_redacted` has just taken out.
192
+ const message = audit.prepareText(describeError(err), call.args);
193
+ audit.append({
194
+ ...base,
195
+ ...mark,
196
+ effect: decision.effect,
197
+ decision: decision.kind,
198
+ rule_id: decision.ruleId,
199
+ reason: decision.reason,
200
+ outcome: "error",
201
+ error: message,
202
+ approval_id: approvalId,
203
+ grant_id: grantId,
204
+ duration_ms: Date.now() - started
205
+ });
206
+ return { kind: "refused", decision, message };
207
+ }
208
+ }
209
+ function describeError(err) {
210
+ if (err instanceof EgressDenied)
211
+ return `Egress refused (${err.code}): ${err.message}`;
212
+ return err?.message ?? String(err);
213
+ }
214
+ /**
215
+ * The text of a tool result that reports its own failure, or null for one
216
+ * that does not. Cut short: it is a pointer for a person, not a transcript.
217
+ */
218
+ export function toolErrorText(result) {
219
+ if (result === null || typeof result !== "object")
220
+ return null;
221
+ const r = result;
222
+ if (r.isError !== true)
223
+ return null;
224
+ const parts = Array.isArray(r.content)
225
+ ? r.content
226
+ .map((c) => (c && typeof c === "object" && typeof c.text === "string" ? c.text : ""))
227
+ .filter((t) => t !== "")
228
+ : [];
229
+ const text = parts.join(" ").replace(/\s+/g, " ").trim() || "the tool reported an error";
230
+ return text.length > 500 ? `${text.slice(0, 500)}…` : text;
231
+ }
@@ -0,0 +1,51 @@
1
+ import type { AuditLog } from "./audit.js";
2
+ import type { ScopedApprovals } from "./approvals.js";
3
+ import type { Effect } from "./policy.js";
4
+ import { type ExposureChange } from "./exposure.js";
5
+ /**
6
+ * Switching one tool off, or handing it back to policy.
7
+ *
8
+ * Three callers now flip this bit — the review console, a hosted gateway's
9
+ * admin API, and the gateway CLI — and the rule about what happens when the
10
+ * audit record cannot be written is different in each direction and easy to
11
+ * get backwards. Copying it three times is how two of the copies end up
12
+ * subtly wrong, so it lives here once:
13
+ *
14
+ * - **Switching off only ever tightens.** If the record cannot be written the
15
+ * change is *kept* and the failure is reported, because undoing a
16
+ * restriction to preserve the log would be trading safety for bookkeeping.
17
+ * - **Switching on loosens**, so an unauditable change is *put back*. A
18
+ * permission that was restored with no record of who restored it is exactly
19
+ * the thing the log exists to prevent.
20
+ * - **Enabling something that was never off writes nothing at all.** A record
21
+ * there would describe a permission change that did not happen.
22
+ *
23
+ * This file is separate from `exposure.ts` because `approvals.ts` imports
24
+ * that one, and this needs `ScopedApprovals`.
25
+ */
26
+ export interface ExposureApplyOptions {
27
+ /** Already bound to one component and one tenant. */
28
+ readonly scoped: ScopedApprovals;
29
+ readonly audit: AuditLog;
30
+ readonly change: ExposureChange;
31
+ /** Who is flipping it, as the audit record will name them. */
32
+ readonly actor: string;
33
+ /** For the record; a gateway's upstream tool may have none. */
34
+ readonly effect: Effect | null | undefined;
35
+ /**
36
+ * Where the flip came from, in prose: "the console", "the admin API",
37
+ * "the gateway CLI". Interpolated into the reason so one code path still
38
+ * produces an honest record for each caller.
39
+ */
40
+ readonly channel: string;
41
+ }
42
+ export interface ExposureApplyResult {
43
+ /** Whether the row's presence actually flipped. A repeat is not a change. */
44
+ readonly changed: boolean;
45
+ /** Set when the change stands but could not be recorded. */
46
+ readonly warning: string | null;
47
+ }
48
+ export declare class ExposureAuditFailed extends Error {
49
+ constructor(message: string);
50
+ }
51
+ export declare function applyExposureChange(options: ExposureApplyOptions): ExposureApplyResult;
@@ -0,0 +1,69 @@
1
+ import { EXPOSURE_DISABLE_RULE, EXPOSURE_ENABLE_RULE } from "./exposure.js";
2
+ export class ExposureAuditFailed extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "ExposureAuditFailed";
6
+ }
7
+ }
8
+ export function applyExposureChange(options) {
9
+ const { scoped, audit, change, actor, effect, channel } = options;
10
+ const name = change.tool;
11
+ /*
12
+ * Taken from the scope rather than passed in, so the record and the row it
13
+ * describes can never disagree about whose switch this is.
14
+ */
15
+ const tenant = scoped.scope.tenant || null;
16
+ const before = scoped.toolExposure(name);
17
+ let warning = null;
18
+ if (change.disabled) {
19
+ const row = scoped.disableTool(name, actor, change.reason);
20
+ try {
21
+ audit.appendStrict({
22
+ tool: name,
23
+ effect: effect ?? null,
24
+ decision: "deny",
25
+ tenant,
26
+ rule_id: EXPOSURE_DISABLE_RULE,
27
+ reason: `${name} switched off via ${channel} by ${actor}` +
28
+ (change.reason ? `: ${change.reason}` : "") +
29
+ "; it is no longer advertised to the model and every call to it is refused",
30
+ outcome: "completed",
31
+ args_redacted: { tool: name, effect: effect ?? null, reason: row.reason }
32
+ });
33
+ }
34
+ catch (err) {
35
+ warning = `${name} was switched off but the audit record failed: ${err.message}`;
36
+ }
37
+ }
38
+ else {
39
+ const removed = scoped.enableTool(name);
40
+ if (removed) {
41
+ try {
42
+ audit.appendStrict({
43
+ tool: name,
44
+ effect: effect ?? null,
45
+ decision: "approve",
46
+ tenant,
47
+ rule_id: EXPOSURE_ENABLE_RULE,
48
+ reason: `${name} switched back on via ${channel} by ${actor} ` +
49
+ `(switched off by ${removed.set_by} at ${new Date(removed.set_at).toISOString()}); ` +
50
+ "policy decides it again from here",
51
+ outcome: "completed",
52
+ args_redacted: { tool: name, effect: effect ?? null }
53
+ });
54
+ }
55
+ catch (err) {
56
+ /*
57
+ * Put back. `set_at` becomes now rather than the original moment,
58
+ * which is a small untruth in the restored row -- but the
59
+ * alternative is a `set_at` parameter on the store existing solely
60
+ * for this path, and the audit record of the failed attempt is where
61
+ * the real history lives.
62
+ */
63
+ scoped.disableTool(name, removed.set_by, removed.reason);
64
+ throw new ExposureAuditFailed(`${name} was left switched off because switching it on could not be audited: ${err.message}`);
65
+ }
66
+ }
67
+ }
68
+ return { changed: (before !== undefined) !== change.disabled, warning };
69
+ }
@@ -0,0 +1,81 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Exposure overrides: taking one tool off the model's menu from the console,
4
+ * without editing `policy.yaml`.
5
+ *
6
+ * The whole point of this project is that `policy.yaml` is the reviewed,
7
+ * version-controlled answer to "what may this agent do", so a console switch
8
+ * must not become a second, unreviewed policy. What makes this one safe is that
9
+ * it is strictly subtractive:
10
+ *
11
+ * - the only state that is ever stored is `disabled`, for one named tool;
12
+ * - a disabled tool is refused before anything else is considered, and is not
13
+ * advertised to the model at all;
14
+ * - "enabling" a tool only *deletes* that row. It restores whatever policy
15
+ * already said, which may well still be deny or approve. There is no stored
16
+ * state that can make a call reachable that `decide()` would have refused.
17
+ *
18
+ * So the switch can always be turned off, and turning it back on hands the
19
+ * question back to policy rather than answering it. A permission that policy
20
+ * does not already grant still belongs in `policy.yaml`.
21
+ *
22
+ * Rows live in the approvals database, which is the existing channel between
23
+ * the console and a running server: both processes already open it, it is
24
+ * already WAL-mode and lock-safe, and a toggle therefore takes effect without
25
+ * restarting anything.
26
+ */
27
+ /** Scoped per server, because one approvals database is shared by default. */
28
+ export interface ToolExposureRow {
29
+ /** The audit `component` of the server this applies to. */
30
+ readonly component: string;
31
+ /** Whose switch it is; "" when no tenant is configured. */
32
+ readonly tenant: string;
33
+ readonly tool: string;
34
+ readonly reason: string;
35
+ readonly set_at: number;
36
+ readonly set_by: string;
37
+ }
38
+ export declare const EXPOSURE_SCHEMA = "\nCREATE TABLE IF NOT EXISTS tool_exposure (\n component TEXT NOT NULL,\n tenant TEXT NOT NULL DEFAULT '',\n tool TEXT NOT NULL,\n reason TEXT NOT NULL,\n set_at INTEGER NOT NULL,\n set_by TEXT NOT NULL,\n PRIMARY KEY (component, tenant, tool)\n);\n";
39
+ /**
40
+ * The rule id a *refusal* caused by an exposure override is recorded under.
41
+ *
42
+ * Distinct from the two below, which record the administrative act of
43
+ * flipping the switch. The string value is in the hash chain and in stored
44
+ * history, so it does not change.
45
+ */
46
+ export declare const EXPOSURE_RULE = "exposure.disabled";
47
+ /** The administrative act of switching a tool off. */
48
+ export declare const EXPOSURE_DISABLE_RULE = "exposure.disable";
49
+ /** The administrative act of handing a tool back to policy. */
50
+ export declare const EXPOSURE_ENABLE_RULE = "exposure.enable";
51
+ /** A caller whose token verified but carries no administrative privilege. */
52
+ export declare const ADMIN_DENIED_RULE = "admin.denied";
53
+ export declare const ExposureChangeSchema: z.ZodObject<{
54
+ tool: z.ZodString;
55
+ disabled: z.ZodBoolean;
56
+ reason: z.ZodDefault<z.ZodString>;
57
+ }, z.core.$strict>;
58
+ export type ExposureChange = z.infer<typeof ExposureChangeSchema>;
59
+ export declare function parseExposureChange(raw: unknown): ExposureChange;
60
+ /**
61
+ * What the *agent* is told when it calls a switched-off tool.
62
+ *
63
+ * Deliberately not `exposureDeniedReason`. That names the operator and repeats
64
+ * the free-text reason they typed, which belongs in the audit log and the
65
+ * console and not in a model's context: the reason may carry the circumstances
66
+ * of an incident, and a model that has been influenced by injected text
67
+ * elsewhere could carry it out through a tool that is still allowed. The
68
+ * upstream never sees either string -- the refusal short-circuits before the
69
+ * call is made -- so the only reader of this is the operator's own agent.
70
+ *
71
+ * It still says enough to be useful: that the tool is off deliberately rather
72
+ * than broken, so the agent reports it instead of retrying.
73
+ */
74
+ export declare const EXPOSURE_AGENT_NOTICE: string;
75
+ /**
76
+ * The full reason, for the audit log and the console.
77
+ *
78
+ * Names who switched it off, when, and why, because that is the record an
79
+ * operator needs later. Not shown to the agent -- see `EXPOSURE_AGENT_NOTICE`.
80
+ */
81
+ export declare function exposureDeniedReason(row: ToolExposureRow): string;
@@ -0,0 +1,65 @@
1
+ import { z } from "zod";
2
+ export const EXPOSURE_SCHEMA = `
3
+ CREATE TABLE IF NOT EXISTS tool_exposure (
4
+ component TEXT NOT NULL,
5
+ tenant TEXT NOT NULL DEFAULT '',
6
+ tool TEXT NOT NULL,
7
+ reason TEXT NOT NULL,
8
+ set_at INTEGER NOT NULL,
9
+ set_by TEXT NOT NULL,
10
+ PRIMARY KEY (component, tenant, tool)
11
+ );
12
+ `;
13
+ /**
14
+ * The rule id a *refusal* caused by an exposure override is recorded under.
15
+ *
16
+ * Distinct from the two below, which record the administrative act of
17
+ * flipping the switch. The string value is in the hash chain and in stored
18
+ * history, so it does not change.
19
+ */
20
+ export const EXPOSURE_RULE = "exposure.disabled";
21
+ /** The administrative act of switching a tool off. */
22
+ export const EXPOSURE_DISABLE_RULE = "exposure.disable";
23
+ /** The administrative act of handing a tool back to policy. */
24
+ export const EXPOSURE_ENABLE_RULE = "exposure.enable";
25
+ /** A caller whose token verified but carries no administrative privilege. */
26
+ export const ADMIN_DENIED_RULE = "admin.denied";
27
+ export const ExposureChangeSchema = z
28
+ .object({
29
+ tool: z.string().min(1),
30
+ disabled: z.boolean(),
31
+ /** Free text, recorded in the audit log and shown wherever it is reviewed. */
32
+ reason: z.string().max(500).default("")
33
+ })
34
+ .strict();
35
+ export function parseExposureChange(raw) {
36
+ return ExposureChangeSchema.parse(raw);
37
+ }
38
+ /**
39
+ * What the *agent* is told when it calls a switched-off tool.
40
+ *
41
+ * Deliberately not `exposureDeniedReason`. That names the operator and repeats
42
+ * the free-text reason they typed, which belongs in the audit log and the
43
+ * console and not in a model's context: the reason may carry the circumstances
44
+ * of an incident, and a model that has been influenced by injected text
45
+ * elsewhere could carry it out through a tool that is still allowed. The
46
+ * upstream never sees either string -- the refusal short-circuits before the
47
+ * call is made -- so the only reader of this is the operator's own agent.
48
+ *
49
+ * It still says enough to be useful: that the tool is off deliberately rather
50
+ * than broken, so the agent reports it instead of retrying.
51
+ */
52
+ export const EXPOSURE_AGENT_NOTICE = "this tool has been switched off by an operator of this gateway. It is not a transient failure, " +
53
+ "and policy was not changed; retrying will not help. Ask whoever runs the gateway if you need it.";
54
+ /**
55
+ * The full reason, for the audit log and the console.
56
+ *
57
+ * Names who switched it off, when, and why, because that is the record an
58
+ * operator needs later. Not shown to the agent -- see `EXPOSURE_AGENT_NOTICE`.
59
+ */
60
+ export function exposureDeniedReason(row) {
61
+ const when = new Date(row.set_at).toISOString();
62
+ return (`tool "${row.tool}" was switched off by ${row.set_by} at ${when}` +
63
+ (row.reason ? `: ${row.reason}` : "") +
64
+ ". Policy was not changed; switching it back on restores whatever policy.yaml already said.");
65
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * A lock file shared between processes, for the files several of them rewrite.
3
+ *
4
+ * The same shape as the audit log's lock (`audit.ts`, `withLock`): an
5
+ * exclusive create (`wx`) of `<path>.lock`, which the filesystem guarantees
6
+ * exactly one process wins, and a reclaim of a lock whose holder died without
7
+ * removing it. Pulled out here because the locked-keys file needs it too --
8
+ * every AI app starts its own gateway process, and a sign-in token that
9
+ * rotates on refresh is rewritten by whichever of them refreshes first.
10
+ *
11
+ * Not reentrant. Taking a lock this process already holds waits for itself and
12
+ * times out, so a caller that needs two levels uses two lock paths.
13
+ */
14
+ export interface FileLockOptions {
15
+ /** How long to wait for another holder before giving up. */
16
+ readonly timeoutMs?: number;
17
+ /**
18
+ * A lock file older than this is a holder that died, and is removed. Must be
19
+ * well above the longest critical section, or a slow holder loses its lock
20
+ * to a waiter that thinks it is dead.
21
+ */
22
+ readonly staleMs?: number;
23
+ /** Named in the timeout message, e.g. "the locked-keys file". */
24
+ readonly what?: string;
25
+ }
26
+ export declare class FileLockTimeout extends Error {
27
+ readonly lockPath: string;
28
+ constructor(lockPath: string, what: string);
29
+ }
30
+ /**
31
+ * Runs `fn` holding `<path>.lock`. Synchronous: for a critical section that is
32
+ * a read and a rename, a few milliseconds long.
33
+ */
34
+ export declare function withFileLock<T>(path: string, fn: () => T, options?: FileLockOptions): T;
35
+ /**
36
+ * The same lock, held across `await`s -- for a critical section that waits on
37
+ * the network, such as refreshing a sign-in token whose refresh token is
38
+ * single-use.
39
+ *
40
+ * While held, the lock file's time is refreshed every second, so a holder that
41
+ * is merely slow (a token endpoint taking eight seconds) is never mistaken for
42
+ * a dead one and has its lock taken away mid-refresh. A holder that really did
43
+ * die stops refreshing and is reclaimed after `staleMs`.
44
+ */
45
+ export declare function withFileLockAsync<T>(path: string, fn: () => Promise<T>, options?: FileLockOptions): Promise<T>;
46
+ /** A file whose permissions let someone other than its owner read it. */
47
+ export declare class FileExposed extends Error {
48
+ readonly path: string;
49
+ readonly mode: number;
50
+ constructor(path: string, mode: number);
51
+ }
52
+ export interface PrivateFileOptions {
53
+ /** Defaults to `process.platform`; injectable for tests. */
54
+ readonly platform?: NodeJS.Platform;
55
+ /** The error to throw instead of `FileExposed`, for a caller with its own words. */
56
+ readonly error?: (path: string, mode: number) => Error;
57
+ }
58
+ /**
59
+ * Throws when a file that holds a credential can be read by group or world.
60
+ *
61
+ * Skipped on Windows: there `stat` reports a synthesized mode (0o666 for any
62
+ * writable file) that says nothing about who can read it -- access is decided
63
+ * by ACLs, which Node does not expose. Checking the mode there refuses every
64
+ * file, which is how the console's token check failed on every Windows
65
+ * machine. A file in the user's profile is private to that user by default.
66
+ *
67
+ * A missing file is not this function's business: it throws the `stat` error
68
+ * (ENOENT) so the caller decides what absence means.
69
+ */
70
+ export declare function assertPrivateFile(path: string, options?: PrivateFileOptions): void;