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.
- package/README.md +19 -3
- package/dist/approvals.d.ts +508 -0
- package/dist/approvals.js +1445 -0
- package/dist/argpath.d.ts +75 -0
- package/dist/argpath.js +189 -0
- package/dist/audit.d.ts +289 -0
- package/dist/audit.js +512 -0
- package/dist/canonical.d.ts +78 -0
- package/dist/canonical.js +146 -0
- package/dist/classify-held.d.ts +47 -0
- package/dist/classify-held.js +60 -0
- package/dist/classify-name.d.ts +55 -0
- package/dist/classify-name.js +255 -0
- package/dist/decide.d.ts +168 -0
- package/dist/decide.js +518 -0
- package/dist/egress.d.ts +123 -0
- package/dist/egress.js +544 -0
- package/dist/enforce.d.ts +78 -0
- package/dist/enforce.js +231 -0
- package/dist/exposure-apply.d.ts +51 -0
- package/dist/exposure-apply.js +69 -0
- package/dist/exposure.d.ts +81 -0
- package/dist/exposure.js +65 -0
- package/dist/file-lock.d.ts +70 -0
- package/dist/file-lock.js +165 -0
- package/dist/glob.d.ts +11 -0
- package/dist/glob.js +55 -0
- package/dist/grants.d.ts +204 -0
- package/dist/grants.js +372 -0
- package/dist/http-util.d.ts +52 -0
- package/dist/http-util.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +36 -0
- package/dist/inventory.d.ts +100 -0
- package/dist/inventory.js +88 -0
- package/dist/ip.d.ts +15 -0
- package/dist/ip.js +186 -0
- package/dist/jwt.d.ts +57 -0
- package/dist/jwt.js +199 -0
- package/dist/live-state.d.ts +76 -0
- package/dist/live-state.js +57 -0
- package/dist/migrate.d.ts +22 -0
- package/dist/migrate.js +318 -0
- package/dist/pins.d.ts +119 -0
- package/dist/pins.js +125 -0
- package/dist/policy-batch.d.ts +89 -0
- package/dist/policy-batch.js +340 -0
- package/dist/policy-source.d.ts +161 -0
- package/dist/policy-source.js +299 -0
- package/dist/policy-write.d.ts +627 -0
- package/dist/policy-write.js +1697 -0
- package/dist/policy.d.ts +456 -0
- package/dist/policy.js +448 -0
- package/dist/redact.d.ts +65 -0
- package/dist/redact.js +191 -0
- package/dist/registry.d.ts +41 -0
- package/dist/registry.js +121 -0
- package/dist/remember-defaults.d.ts +9 -0
- package/dist/remember-defaults.js +9 -0
- package/dist/remember.d.ts +91 -0
- package/dist/remember.js +371 -0
- package/dist/resolve.d.ts +22 -0
- package/dist/resolve.js +34 -0
- package/dist/runtime-state.d.ts +65 -0
- package/dist/runtime-state.js +35 -0
- package/dist/secrets.d.ts +159 -0
- package/dist/secrets.js +361 -0
- package/dist/tenant.d.ts +83 -0
- package/dist/tenant.js +182 -0
- package/dist/unicode.d.ts +40 -0
- package/dist/unicode.js +103 -0
- package/dist/within-host.d.ts +33 -0
- package/dist/within-host.js +91 -0
- package/dist/within-real.d.ts +7 -0
- package/dist/within-real.js +28 -0
- package/package.json +33 -4
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export const TOOL_INVENTORY_SCHEMA = `
|
|
2
|
+
CREATE TABLE IF NOT EXISTS tool_inventory (
|
|
3
|
+
component TEXT NOT NULL,
|
|
4
|
+
tool TEXT NOT NULL,
|
|
5
|
+
pid INTEGER NOT NULL,
|
|
6
|
+
upstream TEXT NOT NULL,
|
|
7
|
+
effect TEXT,
|
|
8
|
+
effect_source TEXT NOT NULL,
|
|
9
|
+
description TEXT NOT NULL,
|
|
10
|
+
raw_description TEXT NOT NULL,
|
|
11
|
+
input_schema TEXT NOT NULL,
|
|
12
|
+
hidden INTEGER NOT NULL,
|
|
13
|
+
injection TEXT,
|
|
14
|
+
discovered_at INTEGER NOT NULL,
|
|
15
|
+
PRIMARY KEY (component, tool)
|
|
16
|
+
);
|
|
17
|
+
`;
|
|
18
|
+
/**
|
|
19
|
+
* Joins a tool surface against one tenant's exposure rows.
|
|
20
|
+
*
|
|
21
|
+
* The single implementation of "what is this tenant's tool surface", so a
|
|
22
|
+
* gateway answering for itself from memory and a console reading what that
|
|
23
|
+
* gateway published cannot answer the same question two different ways. The
|
|
24
|
+
* two differ only in where the tools came from, which is why both entry points
|
|
25
|
+
* below funnel into this one.
|
|
26
|
+
*/
|
|
27
|
+
export function toolSurfaceOf(tools, disabled) {
|
|
28
|
+
const off = new Map(disabled.map((row) => [row.tool, row]));
|
|
29
|
+
return tools.map((tool) => {
|
|
30
|
+
const switchedOff = off.get(tool.tool);
|
|
31
|
+
return {
|
|
32
|
+
name: tool.tool,
|
|
33
|
+
upstream: tool.upstream,
|
|
34
|
+
effect: tool.effect,
|
|
35
|
+
effectSource: tool.effectSource,
|
|
36
|
+
description: tool.description,
|
|
37
|
+
rawDescription: tool.rawDescription,
|
|
38
|
+
inputSchema: tool.inputSchema,
|
|
39
|
+
hiddenByPolicy: tool.hidden,
|
|
40
|
+
injection: tool.injection,
|
|
41
|
+
disabled: switchedOff
|
|
42
|
+
? { reason: switchedOff.reason, setAt: switchedOff.set_at, setBy: switchedOff.set_by }
|
|
43
|
+
: null
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/** The same join, for a reader that has the published rows rather than a gateway. */
|
|
48
|
+
export function toolSurface(inventory, disabled) {
|
|
49
|
+
return toolSurfaceOf(inventory.map(rowToInput), disabled);
|
|
50
|
+
}
|
|
51
|
+
/*
|
|
52
|
+
* A published row came out of the database as text some other process wrote,
|
|
53
|
+
* so neither JSON field is trusted to parse. A field that cannot be read costs
|
|
54
|
+
* itself, not the listing: a console that threw here would show nothing at all
|
|
55
|
+
* because one upstream advertised something odd.
|
|
56
|
+
*/
|
|
57
|
+
function rowToInput(row) {
|
|
58
|
+
return {
|
|
59
|
+
tool: row.tool,
|
|
60
|
+
upstream: row.upstream,
|
|
61
|
+
effect: row.effect,
|
|
62
|
+
effectSource: row.effect_source,
|
|
63
|
+
description: row.description,
|
|
64
|
+
rawDescription: row.raw_description,
|
|
65
|
+
inputSchema: parseSchema(row.input_schema),
|
|
66
|
+
hidden: row.hidden === 1,
|
|
67
|
+
injection: parseInjection(row.injection)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function parseSchema(raw) {
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(raw);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return { type: "object" };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function parseInjection(raw) {
|
|
79
|
+
if (!raw)
|
|
80
|
+
return null;
|
|
81
|
+
try {
|
|
82
|
+
const parsed = JSON.parse(raw);
|
|
83
|
+
return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : null;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
package/dist/ip.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface IpVerdict {
|
|
2
|
+
readonly blocked: boolean;
|
|
3
|
+
readonly reason?: string;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* The IPv4 address an IPv6 literal wraps, as a dotted quad, or null. Covers
|
|
7
|
+
* the mapped (`::ffff:a9fe:a9fe`, which is how a URL parser writes
|
|
8
|
+
* `[::ffff:169.254.169.254]`), translated, NAT64 and 6to4 forms, and the old
|
|
9
|
+
* IPv4-compatible `::a9fe:a9fe`. A caller deciding what kind of place an
|
|
10
|
+
* address is judges the address it wraps (R2 N3).
|
|
11
|
+
*/
|
|
12
|
+
export declare function embeddedIPv4(ip: string): string | null;
|
|
13
|
+
/** True with a reason when this literal address must not be connected to. */
|
|
14
|
+
export declare function classifyAddress(ip: string): IpVerdict;
|
|
15
|
+
export declare function isIpLiteral(host: string): boolean;
|
package/dist/ip.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { isIP, isIPv4 } from "node:net";
|
|
2
|
+
/**
|
|
3
|
+
* Address ranges that must never be reachable from a tool call: loopback,
|
|
4
|
+
* link-local (including the cloud metadata endpoint at 169.254.169.254),
|
|
5
|
+
* private space, CGNAT, and the various documentation and special-use blocks.
|
|
6
|
+
*/
|
|
7
|
+
const V4_BLOCKS = [
|
|
8
|
+
["0.0.0.0", 8, "this-network"],
|
|
9
|
+
["10.0.0.0", 8, "private (RFC1918)"],
|
|
10
|
+
["100.64.0.0", 10, "carrier-grade NAT"],
|
|
11
|
+
["127.0.0.0", 8, "loopback"],
|
|
12
|
+
["169.254.0.0", 16, "link-local / cloud metadata"],
|
|
13
|
+
["172.16.0.0", 12, "private (RFC1918)"],
|
|
14
|
+
["192.0.0.0", 24, "IETF protocol assignments"],
|
|
15
|
+
["192.0.2.0", 24, "documentation (TEST-NET-1)"],
|
|
16
|
+
["192.168.0.0", 16, "private (RFC1918)"],
|
|
17
|
+
["198.18.0.0", 15, "benchmarking"],
|
|
18
|
+
["198.51.100.0", 24, "documentation (TEST-NET-2)"],
|
|
19
|
+
["203.0.113.0", 24, "documentation (TEST-NET-3)"],
|
|
20
|
+
["224.0.0.0", 4, "multicast"],
|
|
21
|
+
["240.0.0.0", 4, "reserved"]
|
|
22
|
+
];
|
|
23
|
+
function v4ToInt(ip) {
|
|
24
|
+
const parts = ip.split(".");
|
|
25
|
+
if (parts.length !== 4)
|
|
26
|
+
return null;
|
|
27
|
+
let out = 0;
|
|
28
|
+
for (const part of parts) {
|
|
29
|
+
if (!/^\d{1,3}$/.test(part))
|
|
30
|
+
return null;
|
|
31
|
+
const n = Number(part);
|
|
32
|
+
if (n > 255)
|
|
33
|
+
return null;
|
|
34
|
+
out = (out << 8) | n;
|
|
35
|
+
}
|
|
36
|
+
return out >>> 0;
|
|
37
|
+
}
|
|
38
|
+
function inV4Block(ip, base, bits) {
|
|
39
|
+
const baseInt = v4ToInt(base);
|
|
40
|
+
if (baseInt === null)
|
|
41
|
+
return false;
|
|
42
|
+
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
|
43
|
+
return (ip & mask) === (baseInt & mask);
|
|
44
|
+
}
|
|
45
|
+
function classifyV4(ip) {
|
|
46
|
+
const n = v4ToInt(ip);
|
|
47
|
+
if (n === null)
|
|
48
|
+
return { blocked: true, reason: `unparseable IPv4 address ${ip}` };
|
|
49
|
+
if (n === 0xffffffff)
|
|
50
|
+
return { blocked: true, reason: "broadcast address" };
|
|
51
|
+
for (const [base, bits, label] of V4_BLOCKS) {
|
|
52
|
+
if (inV4Block(n, base, bits))
|
|
53
|
+
return { blocked: true, reason: `${ip} is in ${base}/${bits} (${label})` };
|
|
54
|
+
}
|
|
55
|
+
return { blocked: false };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The 16 bytes of an IPv6 address, or null if it is not one.
|
|
59
|
+
*
|
|
60
|
+
* Parsed to bytes rather than matched as text, because the text is not
|
|
61
|
+
* stable: the same address can be written with a dotted IPv4 tail or in hex,
|
|
62
|
+
* compressed or expanded, and a URL parser rewrites one into another. Every
|
|
63
|
+
* prefix test below is then a comparison of numbers, which has one answer.
|
|
64
|
+
*/
|
|
65
|
+
function parseV6(ip) {
|
|
66
|
+
let addr = ip.replace(/^\[|\]$/g, "").split("%")[0].toLowerCase();
|
|
67
|
+
// A dotted IPv4 tail occupies the last two groups.
|
|
68
|
+
const dotted = /^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(addr);
|
|
69
|
+
if (dotted) {
|
|
70
|
+
const n = v4ToInt(dotted[2]);
|
|
71
|
+
if (n === null)
|
|
72
|
+
return null;
|
|
73
|
+
addr = `${dotted[1]}${(n >>> 16).toString(16)}:${(n & 0xffff).toString(16)}`;
|
|
74
|
+
}
|
|
75
|
+
const halves = addr.split("::");
|
|
76
|
+
if (halves.length > 2)
|
|
77
|
+
return null;
|
|
78
|
+
const toGroups = (part) => (part.length === 0 ? [] : part.split(":"));
|
|
79
|
+
let groups;
|
|
80
|
+
if (halves.length === 2) {
|
|
81
|
+
const head = toGroups(halves[0]);
|
|
82
|
+
const tail = toGroups(halves[1]);
|
|
83
|
+
const fill = 8 - head.length - tail.length;
|
|
84
|
+
if (fill < 0)
|
|
85
|
+
return null;
|
|
86
|
+
groups = [...head, ...Array(fill).fill("0"), ...tail];
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
groups = toGroups(halves[0]);
|
|
90
|
+
}
|
|
91
|
+
if (groups.length !== 8)
|
|
92
|
+
return null;
|
|
93
|
+
const bytes = [];
|
|
94
|
+
for (const group of groups) {
|
|
95
|
+
if (!/^[0-9a-f]{1,4}$/.test(group))
|
|
96
|
+
return null;
|
|
97
|
+
const value = parseInt(group, 16);
|
|
98
|
+
bytes.push(value >>> 8, value & 0xff);
|
|
99
|
+
}
|
|
100
|
+
return bytes;
|
|
101
|
+
}
|
|
102
|
+
/** True when the first `bits` bits of an address equal those of `prefix`. */
|
|
103
|
+
function hasPrefix(bytes, prefix, bits) {
|
|
104
|
+
for (let i = 0; i < Math.ceil(bits / 8); i++) {
|
|
105
|
+
const remaining = bits - i * 8;
|
|
106
|
+
const mask = remaining >= 8 ? 0xff : (0xff << (8 - remaining)) & 0xff;
|
|
107
|
+
if ((bytes[i] & mask) !== ((prefix[i] ?? 0) & mask))
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
const dottedQuad = (bytes, at) => `${bytes[at]}.${bytes[at + 1]}.${bytes[at + 2]}.${bytes[at + 3]}`;
|
|
113
|
+
/*
|
|
114
|
+
* Prefixes under which an IPv6 address is a wrapper around an IPv4 one, with
|
|
115
|
+
* the offset of the embedded address. A connection to the wrapper is a
|
|
116
|
+
* connection to what it wraps, so the wrapped address is what gets judged.
|
|
117
|
+
*/
|
|
118
|
+
const EMBEDS_V4 = [
|
|
119
|
+
{ prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff], bits: 96, at: 12, label: "IPv4-mapped" },
|
|
120
|
+
{ prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0], bits: 96, at: 12, label: "IPv4-translated" },
|
|
121
|
+
{ prefix: [0, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0], bits: 96, at: 12, label: "NAT64" },
|
|
122
|
+
{ prefix: [0x20, 0x02], bits: 16, at: 2, label: "6to4" }
|
|
123
|
+
];
|
|
124
|
+
/* IPv6 space that is not the public internet, whatever it contains. */
|
|
125
|
+
const V6_BLOCKS = [
|
|
126
|
+
// Includes ::, ::1 and the deprecated IPv4-compatible addresses.
|
|
127
|
+
{ prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], bits: 96, label: "::/96 (loopback, unspecified, IPv4-compatible)" },
|
|
128
|
+
{ prefix: [0, 0x64, 0xff, 0x9b, 0, 0x01], bits: 48, label: "64:ff9b:1::/48 (local-use NAT64)" },
|
|
129
|
+
{ prefix: [0x01, 0, 0, 0, 0, 0, 0, 0], bits: 64, label: "100::/64 (discard-only)" },
|
|
130
|
+
{ prefix: [0x20, 0x01, 0, 0], bits: 32, label: "2001::/32 (Teredo tunnelling)" },
|
|
131
|
+
{ prefix: [0x20, 0x01, 0x0d, 0xb8], bits: 32, label: "2001:db8::/32 (documentation)" },
|
|
132
|
+
{ prefix: [0xfc], bits: 7, label: "fc00::/7 (unique local)" },
|
|
133
|
+
{ prefix: [0xfe, 0x80], bits: 10, label: "fe80::/10 (link-local)" },
|
|
134
|
+
{ prefix: [0xfe, 0xc0], bits: 10, label: "fec0::/10 (site-local)" },
|
|
135
|
+
{ prefix: [0xff], bits: 8, label: "ff00::/8 (multicast)" }
|
|
136
|
+
];
|
|
137
|
+
function classifyV6(ip) {
|
|
138
|
+
const bytes = parseV6(ip);
|
|
139
|
+
if (!bytes)
|
|
140
|
+
return { blocked: true, reason: `unparseable IPv6 address ${ip}` };
|
|
141
|
+
for (const form of EMBEDS_V4) {
|
|
142
|
+
if (!hasPrefix(bytes, form.prefix, form.bits))
|
|
143
|
+
continue;
|
|
144
|
+
const inner = classifyV4(dottedQuad(bytes, form.at));
|
|
145
|
+
return inner.blocked
|
|
146
|
+
? { blocked: true, reason: `${ip} is an ${form.label} address that embeds ${inner.reason}` }
|
|
147
|
+
: { blocked: false };
|
|
148
|
+
}
|
|
149
|
+
for (const block of V6_BLOCKS) {
|
|
150
|
+
if (hasPrefix(bytes, block.prefix, block.bits)) {
|
|
151
|
+
return { blocked: true, reason: `${ip} is in ${block.label}` };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { blocked: false };
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* The IPv4 address an IPv6 literal wraps, as a dotted quad, or null. Covers
|
|
158
|
+
* the mapped (`::ffff:a9fe:a9fe`, which is how a URL parser writes
|
|
159
|
+
* `[::ffff:169.254.169.254]`), translated, NAT64 and 6to4 forms, and the old
|
|
160
|
+
* IPv4-compatible `::a9fe:a9fe`. A caller deciding what kind of place an
|
|
161
|
+
* address is judges the address it wraps (R2 N3).
|
|
162
|
+
*/
|
|
163
|
+
export function embeddedIPv4(ip) {
|
|
164
|
+
if (isIP(ip.replace(/^\[|\]$/g, "").split("%")[0]) !== 6)
|
|
165
|
+
return null;
|
|
166
|
+
const bytes = parseV6(ip);
|
|
167
|
+
if (!bytes)
|
|
168
|
+
return null;
|
|
169
|
+
for (const form of EMBEDS_V4)
|
|
170
|
+
if (hasPrefix(bytes, form.prefix, form.bits))
|
|
171
|
+
return dottedQuad(bytes, form.at);
|
|
172
|
+
// IPv4-compatible: 96 zero bits, then an address that isn't :: or ::1.
|
|
173
|
+
if (hasPrefix(bytes, Array(12).fill(0), 96) && (bytes[12] | bytes[13]) !== 0)
|
|
174
|
+
return dottedQuad(bytes, 12);
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
/** True with a reason when this literal address must not be connected to. */
|
|
178
|
+
export function classifyAddress(ip) {
|
|
179
|
+
const family = isIP(ip.replace(/^\[|\]$/g, "").split("%")[0]);
|
|
180
|
+
if (family === 0)
|
|
181
|
+
return { blocked: true, reason: `not an IP address: ${ip}` };
|
|
182
|
+
return isIPv4(ip) ? classifyV4(ip) : classifyV6(ip);
|
|
183
|
+
}
|
|
184
|
+
export function isIpLiteral(host) {
|
|
185
|
+
return isIP(host.replace(/^\[|\]$/g, "")) !== 0;
|
|
186
|
+
}
|
package/dist/jwt.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { EgressGuard } from "./egress.js";
|
|
2
|
+
import type { JwtVerifiedSource } from "./policy.js";
|
|
3
|
+
export interface TenantClaimResult {
|
|
4
|
+
readonly tenant: string;
|
|
5
|
+
/** For the audit record: who the token says is calling. */
|
|
6
|
+
readonly subject: string | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* The scopes the token carries, from `scope` or `scp`.
|
|
9
|
+
*
|
|
10
|
+
* Read only so an admin surface can require one. `azp` and `client_id` are
|
|
11
|
+
* still discarded: a client identifier says who is asking, not what they
|
|
12
|
+
* are allowed to do, and treating one as the other is how an application
|
|
13
|
+
* id becomes a privilege.
|
|
14
|
+
*/
|
|
15
|
+
readonly scopes: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Verifies bearer tokens and reads the tenant claim out of them.
|
|
19
|
+
*
|
|
20
|
+
* Built once and reused: `createRemoteJWKSet` caches the key set and handles
|
|
21
|
+
* rotation, so a per-request instance would fetch the JWKS on every call and
|
|
22
|
+
* hand an attacker a trivial amplifier against the authorization server.
|
|
23
|
+
*/
|
|
24
|
+
export declare class TenantVerifier {
|
|
25
|
+
private readonly source;
|
|
26
|
+
/**
|
|
27
|
+
* Used to fetch the JWKS. Not optional, and not a plain `fetch`: a URL
|
|
28
|
+
* taken from configuration is still a URL this process will dial, so it
|
|
29
|
+
* goes through the same allowlist, private-address check and DNS pinning
|
|
30
|
+
* as every other outbound request. A `jwks_uri` pointing at a cloud
|
|
31
|
+
* metadata endpoint is refused for the same reason an upstream would be.
|
|
32
|
+
*/
|
|
33
|
+
private readonly egress;
|
|
34
|
+
private readonly keys;
|
|
35
|
+
constructor(source: JwtVerifiedSource,
|
|
36
|
+
/**
|
|
37
|
+
* Used to fetch the JWKS. Not optional, and not a plain `fetch`: a URL
|
|
38
|
+
* taken from configuration is still a URL this process will dial, so it
|
|
39
|
+
* goes through the same allowlist, private-address check and DNS pinning
|
|
40
|
+
* as every other outbound request. A `jwks_uri` pointing at a cloud
|
|
41
|
+
* metadata endpoint is refused for the same reason an upstream would be.
|
|
42
|
+
*/
|
|
43
|
+
egress: EgressGuard);
|
|
44
|
+
private loadKeys;
|
|
45
|
+
/**
|
|
46
|
+
* The tenant this token speaks for, or a `TenantError` naming why not.
|
|
47
|
+
*
|
|
48
|
+
* Every refusal is the same error type, and the message names the cause.
|
|
49
|
+
* That message is for the operator's log. Whatever serves these errors over
|
|
50
|
+
* the wire must not send it: a bad signature, an unknown key, the wrong
|
|
51
|
+
* audience and an expired token are all "this token does not establish a
|
|
52
|
+
* tenant" to a caller, because telling them apart is a probing oracle.
|
|
53
|
+
*/
|
|
54
|
+
verify(token: string): Promise<TenantClaimResult>;
|
|
55
|
+
}
|
|
56
|
+
/** The bearer token on a request, or undefined. */
|
|
57
|
+
export declare function bearerToken(headers: Record<string, string | string[] | undefined>, headerName?: string): string | undefined;
|
package/dist/jwt.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { createRemoteJWKSet, customFetch, errors, importSPKI, jwtVerify } from "jose";
|
|
2
|
+
import { createPublicKey } from "node:crypto";
|
|
3
|
+
import { TenantError, normalizeTenantKey } from "./tenant.js";
|
|
4
|
+
/**
|
|
5
|
+
* Deriving a tenant from a token the caller supplied.
|
|
6
|
+
*
|
|
7
|
+
* Everywhere else in this project the tenant comes from the deployment: a
|
|
8
|
+
* static value, an environment variable, a claim in a credential the operator
|
|
9
|
+
* configured. Those are trustworthy because nothing the agent controls reaches
|
|
10
|
+
* them, which is exactly what `jwt-claim`'s comment says — "our own
|
|
11
|
+
* credential, not attacker-supplied input, so there is nothing to forge".
|
|
12
|
+
*
|
|
13
|
+
* A hosted gateway breaks that assumption. The token arrives per request, from
|
|
14
|
+
* the caller, and the tenant read out of it becomes the key that every stored
|
|
15
|
+
* row is filed under. If the signature is not checked, anyone can rename
|
|
16
|
+
* themselves into another customer's scope and redeem their approvals: the
|
|
17
|
+
* upstream API would still refuse their data, but the gateway's own state —
|
|
18
|
+
* the approval queue, the standing grants, the exposure switches — would be
|
|
19
|
+
* wide open. The gateway would be the vulnerability.
|
|
20
|
+
*
|
|
21
|
+
* So this is a separate source kind rather than a flag on the old one. There
|
|
22
|
+
* is no configuration that turns verification off, and `jwt-claim` keeps its
|
|
23
|
+
* original meaning rather than quietly becoming unsafe.
|
|
24
|
+
*
|
|
25
|
+
* Verification is `jose`, not hand-rolled. Algorithm confusion and `alg: none`
|
|
26
|
+
* are the classic ways a bespoke JWT check fails open, and a tool that exists
|
|
27
|
+
* to be the careful layer should not be improvising its own crypto.
|
|
28
|
+
*/
|
|
29
|
+
/** Only asymmetric signatures, and only two. */
|
|
30
|
+
const ALGORITHMS = ["RS256", "ES256"];
|
|
31
|
+
/** Which of the two a pinned PEM is for. */
|
|
32
|
+
function algorithmOf(pem) {
|
|
33
|
+
let type;
|
|
34
|
+
try {
|
|
35
|
+
type = createPublicKey(pem).asymmetricKeyType ?? null;
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
throw new TenantError(`tenant.source.public_key is not a readable public key: ${err.message}`);
|
|
39
|
+
}
|
|
40
|
+
if (type === "rsa" || type === "rsa-pss")
|
|
41
|
+
return "RS256";
|
|
42
|
+
if (type === "ec")
|
|
43
|
+
return "ES256";
|
|
44
|
+
throw new TenantError(`tenant.source.public_key is ${type ?? "of an unknown type"}; this gateway verifies ` +
|
|
45
|
+
`${ALGORITHMS.join(" and ")} only.`);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Verifies bearer tokens and reads the tenant claim out of them.
|
|
49
|
+
*
|
|
50
|
+
* Built once and reused: `createRemoteJWKSet` caches the key set and handles
|
|
51
|
+
* rotation, so a per-request instance would fetch the JWKS on every call and
|
|
52
|
+
* hand an attacker a trivial amplifier against the authorization server.
|
|
53
|
+
*/
|
|
54
|
+
export class TenantVerifier {
|
|
55
|
+
source;
|
|
56
|
+
egress;
|
|
57
|
+
keys;
|
|
58
|
+
constructor(source,
|
|
59
|
+
/**
|
|
60
|
+
* Used to fetch the JWKS. Not optional, and not a plain `fetch`: a URL
|
|
61
|
+
* taken from configuration is still a URL this process will dial, so it
|
|
62
|
+
* goes through the same allowlist, private-address check and DNS pinning
|
|
63
|
+
* as every other outbound request. A `jwks_uri` pointing at a cloud
|
|
64
|
+
* metadata endpoint is refused for the same reason an upstream would be.
|
|
65
|
+
*/
|
|
66
|
+
egress) {
|
|
67
|
+
this.source = source;
|
|
68
|
+
this.egress = egress;
|
|
69
|
+
this.keys = this.loadKeys();
|
|
70
|
+
// Nothing awaits this at construction; swallow so an unreachable JWKS at
|
|
71
|
+
// boot surfaces on the first call rather than as an unhandled rejection.
|
|
72
|
+
void this.keys.catch(() => undefined);
|
|
73
|
+
}
|
|
74
|
+
async loadKeys() {
|
|
75
|
+
if (this.source.public_key) {
|
|
76
|
+
/*
|
|
77
|
+
* The algorithm is read off the key rather than assumed. Hard-coding
|
|
78
|
+
* one here meant a pinned EC key failed to import at all, with "invalid
|
|
79
|
+
* key type" surfacing as "the token could not be verified" — a
|
|
80
|
+
* configuration error wearing the costume of a bad token, which is
|
|
81
|
+
* about the worst place to put that disguise.
|
|
82
|
+
*/
|
|
83
|
+
return importSPKI(this.source.public_key, algorithmOf(this.source.public_key));
|
|
84
|
+
}
|
|
85
|
+
return createRemoteJWKSet(new URL(this.source.jwks_uri), {
|
|
86
|
+
[customFetch]: async (url, init) => {
|
|
87
|
+
const response = await this.egress.fetch(url, {
|
|
88
|
+
method: "GET",
|
|
89
|
+
headers: Object.fromEntries(init.headers.entries()),
|
|
90
|
+
...(init.signal ? { signal: init.signal } : {})
|
|
91
|
+
});
|
|
92
|
+
return new Response(response.body, {
|
|
93
|
+
status: response.status,
|
|
94
|
+
headers: { "content-type": "application/json" }
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The tenant this token speaks for, or a `TenantError` naming why not.
|
|
101
|
+
*
|
|
102
|
+
* Every refusal is the same error type, and the message names the cause.
|
|
103
|
+
* That message is for the operator's log. Whatever serves these errors over
|
|
104
|
+
* the wire must not send it: a bad signature, an unknown key, the wrong
|
|
105
|
+
* audience and an expired token are all "this token does not establish a
|
|
106
|
+
* tenant" to a caller, because telling them apart is a probing oracle.
|
|
107
|
+
*/
|
|
108
|
+
async verify(token) {
|
|
109
|
+
let payload;
|
|
110
|
+
try {
|
|
111
|
+
const keys = await this.keys;
|
|
112
|
+
({ payload } = await jwtVerify(token, keys, {
|
|
113
|
+
issuer: this.source.issuer,
|
|
114
|
+
audience: this.source.audience,
|
|
115
|
+
// Pinned, never read from the token's own header: letting the token
|
|
116
|
+
// choose its algorithm is how `alg: none` and HS256-signed-with-the-
|
|
117
|
+
// public-key attacks get in.
|
|
118
|
+
algorithms: [...ALGORITHMS],
|
|
119
|
+
requiredClaims: ["iss", "aud", "exp"]
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
throw new TenantError(describeFailure(err));
|
|
124
|
+
}
|
|
125
|
+
const raw = payload[this.source.claim];
|
|
126
|
+
if (raw === undefined || raw === null || raw === "") {
|
|
127
|
+
throw new TenantError(`the token is valid but carries no ${JSON.stringify(this.source.claim)} claim, ` +
|
|
128
|
+
"so there is no tenant to scope this call to");
|
|
129
|
+
}
|
|
130
|
+
if (typeof raw !== "string" && typeof raw !== "number") {
|
|
131
|
+
throw new TenantError(`the ${JSON.stringify(this.source.claim)} claim is a ${typeof raw}; a tenant identifier must be a string`);
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
tenant: normalizeTenantKey(String(raw)),
|
|
135
|
+
subject: typeof payload.sub === "string" ? payload.sub : undefined,
|
|
136
|
+
scopes: readScopes(payload)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Both spellings, unioned.
|
|
142
|
+
*
|
|
143
|
+
* `scope` is OAuth 2's space-delimited string; `scp` is the array several
|
|
144
|
+
* issuers use instead, and some of those send it as a string anyway. Parsed
|
|
145
|
+
* into exact tokens here so the comparison is never a substring test —
|
|
146
|
+
* `hmcp:admin-readonly` must not satisfy a requirement for `hmcp:admin`.
|
|
147
|
+
*/
|
|
148
|
+
function readScopes(payload) {
|
|
149
|
+
const out = new Set();
|
|
150
|
+
const add = (value) => {
|
|
151
|
+
if (typeof value === "string") {
|
|
152
|
+
for (const part of value.split(/\s+/))
|
|
153
|
+
if (part)
|
|
154
|
+
out.add(part);
|
|
155
|
+
}
|
|
156
|
+
else if (Array.isArray(value)) {
|
|
157
|
+
for (const item of value)
|
|
158
|
+
if (typeof item === "string" && item)
|
|
159
|
+
out.add(item);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
add(payload["scope"]);
|
|
163
|
+
add(payload["scp"]);
|
|
164
|
+
return [...out];
|
|
165
|
+
}
|
|
166
|
+
/** Keeps the cause in the log without turning the response into an oracle. */
|
|
167
|
+
function describeFailure(err) {
|
|
168
|
+
if (err instanceof errors.JWTExpired)
|
|
169
|
+
return "the token has expired";
|
|
170
|
+
if (err instanceof errors.JWTClaimValidationFailed) {
|
|
171
|
+
return `the token's ${err.claim} claim is not accepted here`;
|
|
172
|
+
}
|
|
173
|
+
if (err instanceof errors.JWSSignatureVerificationFailed)
|
|
174
|
+
return "the token's signature does not verify";
|
|
175
|
+
if (err instanceof errors.JWKSNoMatchingKey) {
|
|
176
|
+
return "no key in the configured JWKS matches this token";
|
|
177
|
+
}
|
|
178
|
+
if (err instanceof errors.JOSEAlgNotAllowed) {
|
|
179
|
+
return `the token is signed with an algorithm this gateway does not accept (allowed: ${ALGORITHMS.join(", ")})`;
|
|
180
|
+
}
|
|
181
|
+
if (err instanceof errors.JWKSTimeout || err?.name === "EgressDenied") {
|
|
182
|
+
return `the key set could not be fetched: ${err.message}`;
|
|
183
|
+
}
|
|
184
|
+
return `the token could not be verified: ${err.message}`;
|
|
185
|
+
}
|
|
186
|
+
/** The bearer token on a request, or undefined. */
|
|
187
|
+
export function bearerToken(headers, headerName = "authorization") {
|
|
188
|
+
const wanted = headerName.toLowerCase();
|
|
189
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
190
|
+
if (key.toLowerCase() !== wanted)
|
|
191
|
+
continue;
|
|
192
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
193
|
+
if (!raw)
|
|
194
|
+
continue;
|
|
195
|
+
const match = /^bearer\s+(.+)$/i.exec(raw.trim());
|
|
196
|
+
return match ? match[1].trim() : raw.trim();
|
|
197
|
+
}
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a running gateway says about each of its servers, so the console can
|
|
3
|
+
* show "connected", "failing because ..." or "sign in again" -- and know when
|
|
4
|
+
* a change written to gateway.yaml has actually been applied.
|
|
5
|
+
*
|
|
6
|
+
* Every gateway process writes its own row (several AI apps can each run one
|
|
7
|
+
* for the same gateway.yaml) on its heartbeat. Rows live in the approvals
|
|
8
|
+
* database next to `runtime_state`, created with IF NOT EXISTS so no
|
|
9
|
+
* migration is needed.
|
|
10
|
+
*
|
|
11
|
+
* CONTRACT (phase 0). Types and SQL are fixed; the read/write methods on
|
|
12
|
+
* ApprovalStore are implemented by workstream A.
|
|
13
|
+
*/
|
|
14
|
+
/** Why a server is not working, as a code the console turns into words. */
|
|
15
|
+
export declare const UPSTREAM_PROBLEM_CODES: readonly ["command-not-found", "runtime-missing", "runtime-not-running", "folder-missing", "secret-missing", "auth-rejected", "needs-sign-in", "timeout", "egress-refused", "network", "tls", "exited", "not-mcp", "sse-only", "unknown"];
|
|
16
|
+
export type UpstreamProblemCode = (typeof UPSTREAM_PROBLEM_CODES)[number];
|
|
17
|
+
export interface UpstreamProblem {
|
|
18
|
+
code: UpstreamProblemCode;
|
|
19
|
+
/** One technical sentence, shown under "Details". Never contains a secret value. */
|
|
20
|
+
message: string;
|
|
21
|
+
detail?: {
|
|
22
|
+
/** For runtime-missing / runtime-not-running / command-not-found. */
|
|
23
|
+
runtime?: "node" | "npx" | "uv" | "uvx" | "docker" | "python" | "git" | string;
|
|
24
|
+
command?: string;
|
|
25
|
+
/** For folder-missing. */
|
|
26
|
+
path?: string;
|
|
27
|
+
/** For egress-refused / network / tls. */
|
|
28
|
+
host?: string;
|
|
29
|
+
/** HTTP status, for auth-rejected / not-mcp. */
|
|
30
|
+
status?: number;
|
|
31
|
+
/** For secret-missing / needs-sign-in. */
|
|
32
|
+
secret?: string;
|
|
33
|
+
/** The last few lines the server wrote, secrets not included. */
|
|
34
|
+
stderrTail?: string[];
|
|
35
|
+
exitCode?: number | null;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export type UpstreamLiveStateName = "connecting" | "connected" | "failed" | "needs-sign-in" | "stopped";
|
|
39
|
+
export interface UpstreamLiveState {
|
|
40
|
+
name: string;
|
|
41
|
+
state: UpstreamLiveStateName;
|
|
42
|
+
problem?: UpstreamProblem;
|
|
43
|
+
/** ISO time of the last state change. */
|
|
44
|
+
since: string;
|
|
45
|
+
/** Connect attempts since the last success. */
|
|
46
|
+
attempts: number;
|
|
47
|
+
/** ISO time of the next automatic retry, when one is scheduled. */
|
|
48
|
+
next_retry_at?: string;
|
|
49
|
+
tool_count: number;
|
|
50
|
+
}
|
|
51
|
+
/** One gateway process's view. */
|
|
52
|
+
export interface LiveConfigStateRow {
|
|
53
|
+
component: string;
|
|
54
|
+
pid: number;
|
|
55
|
+
/** Digest of the gateway.yaml text this process has applied. */
|
|
56
|
+
config_digest: string;
|
|
57
|
+
applied_at: string;
|
|
58
|
+
/** Set when the file changed in a way that cannot be applied live. */
|
|
59
|
+
refusal: string | null;
|
|
60
|
+
upstreams: UpstreamLiveState[];
|
|
61
|
+
/** ISO heartbeat time; a row older than a few seconds is a dead process. */
|
|
62
|
+
heartbeat_at: string;
|
|
63
|
+
}
|
|
64
|
+
/** A request from the console to a running gateway. */
|
|
65
|
+
export interface LiveRequest {
|
|
66
|
+
id: number;
|
|
67
|
+
component: string;
|
|
68
|
+
upstream: string;
|
|
69
|
+
kind: "retry";
|
|
70
|
+
created_at: string;
|
|
71
|
+
}
|
|
72
|
+
export declare const LIVE_STATE_SQL = "\nCREATE TABLE IF NOT EXISTS live_config_state (\n component TEXT NOT NULL,\n pid INTEGER NOT NULL,\n config_digest TEXT NOT NULL,\n applied_at TEXT NOT NULL,\n refusal TEXT,\n upstreams TEXT NOT NULL,\n heartbeat_at TEXT NOT NULL,\n PRIMARY KEY (component, pid)\n);\nCREATE TABLE IF NOT EXISTS live_requests (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n component TEXT NOT NULL,\n upstream TEXT NOT NULL,\n kind TEXT NOT NULL,\n created_at TEXT NOT NULL\n);\n";
|
|
73
|
+
/** A row whose heartbeat is older than this belongs to a process that is gone. */
|
|
74
|
+
export declare const LIVE_STATE_STALE_MS = 10000;
|
|
75
|
+
/** Whether a row's heartbeat is recent enough that its process is still running. */
|
|
76
|
+
export declare function liveStateFresh(row: Pick<LiveConfigStateRow, "heartbeat_at">, now?: number): boolean;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a running gateway says about each of its servers, so the console can
|
|
3
|
+
* show "connected", "failing because ..." or "sign in again" -- and know when
|
|
4
|
+
* a change written to gateway.yaml has actually been applied.
|
|
5
|
+
*
|
|
6
|
+
* Every gateway process writes its own row (several AI apps can each run one
|
|
7
|
+
* for the same gateway.yaml) on its heartbeat. Rows live in the approvals
|
|
8
|
+
* database next to `runtime_state`, created with IF NOT EXISTS so no
|
|
9
|
+
* migration is needed.
|
|
10
|
+
*
|
|
11
|
+
* CONTRACT (phase 0). Types and SQL are fixed; the read/write methods on
|
|
12
|
+
* ApprovalStore are implemented by workstream A.
|
|
13
|
+
*/
|
|
14
|
+
/** Why a server is not working, as a code the console turns into words. */
|
|
15
|
+
export const UPSTREAM_PROBLEM_CODES = [
|
|
16
|
+
"command-not-found", // the program to start does not exist (npx, docker, a path)
|
|
17
|
+
"runtime-missing", // a known runtime is not installed: node, uv, docker, python
|
|
18
|
+
"runtime-not-running", // installed but not running (Docker Desktop closed)
|
|
19
|
+
"folder-missing", // a folder it was given does not exist
|
|
20
|
+
"secret-missing", // a locked key it refers to is not in the locked-keys file
|
|
21
|
+
"auth-rejected", // the server said the key is wrong (401/403)
|
|
22
|
+
"needs-sign-in", // sign-in expired or was revoked; a person has to sign in again
|
|
23
|
+
"timeout", // it started but never answered
|
|
24
|
+
"egress-refused", // the network rules do not allow its address
|
|
25
|
+
"network", // could not reach it: DNS, refused, reset
|
|
26
|
+
"tls", // its certificate could not be checked
|
|
27
|
+
"exited", // the program started and then quit
|
|
28
|
+
"not-mcp", // something answered, but not an MCP server
|
|
29
|
+
"sse-only", // a remote server that only speaks the old SSE transport
|
|
30
|
+
"unknown"
|
|
31
|
+
];
|
|
32
|
+
export const LIVE_STATE_SQL = `
|
|
33
|
+
CREATE TABLE IF NOT EXISTS live_config_state (
|
|
34
|
+
component TEXT NOT NULL,
|
|
35
|
+
pid INTEGER NOT NULL,
|
|
36
|
+
config_digest TEXT NOT NULL,
|
|
37
|
+
applied_at TEXT NOT NULL,
|
|
38
|
+
refusal TEXT,
|
|
39
|
+
upstreams TEXT NOT NULL,
|
|
40
|
+
heartbeat_at TEXT NOT NULL,
|
|
41
|
+
PRIMARY KEY (component, pid)
|
|
42
|
+
);
|
|
43
|
+
CREATE TABLE IF NOT EXISTS live_requests (
|
|
44
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
45
|
+
component TEXT NOT NULL,
|
|
46
|
+
upstream TEXT NOT NULL,
|
|
47
|
+
kind TEXT NOT NULL,
|
|
48
|
+
created_at TEXT NOT NULL
|
|
49
|
+
);
|
|
50
|
+
`;
|
|
51
|
+
/** A row whose heartbeat is older than this belongs to a process that is gone. */
|
|
52
|
+
export const LIVE_STATE_STALE_MS = 10_000;
|
|
53
|
+
/** Whether a row's heartbeat is recent enough that its process is still running. */
|
|
54
|
+
export function liveStateFresh(row, now = Date.now()) {
|
|
55
|
+
const beat = Date.parse(row.heartbeat_at);
|
|
56
|
+
return Number.isFinite(beat) && now - beat <= LIVE_STATE_STALE_MS;
|
|
57
|
+
}
|