@metamynd/agentsafe-http-gateway 0.1.1
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/LICENSE +21 -0
- package/README.md +58 -0
- package/gateway.mjs +74 -0
- package/package.json +60 -0
- package/route-match.mjs +47 -0
- package/server.mjs +88 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MetaMynd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# AgentSafe HTTP interception gateway (SAFR §17)
|
|
2
|
+
|
|
3
|
+
A **generic reverse proxy** that governs *arbitrary* HTTP calls — not just MCP. Put it in front of
|
|
4
|
+
any upstream service; requests matching a **protected route** are re-evaluated through the AgentSafe
|
|
5
|
+
gate before they are forwarded, and everything else passes through untouched. Zero dependencies
|
|
6
|
+
(`node:http` + built-in `fetch` + the zero-dep `agentsafe-mcp-guard`).
|
|
7
|
+
|
|
8
|
+
This closes the gap where governance only sat at the MCP boundary + hand-written demo gateways — now
|
|
9
|
+
a legacy or third-party agent that speaks plain HTTP can be governed at the network edge.
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
agent → [ HTTP gateway ] → upstream service
|
|
15
|
+
│
|
|
16
|
+
├─ route not protected → forward as-is
|
|
17
|
+
└─ route protected:
|
|
18
|
+
verifyRequest(signed) → allow/observe → forward upstream (+ x-agentsafe-decision)
|
|
19
|
+
→ block/escalate → 403 (upstream never called)
|
|
20
|
+
→ no signed request → 401
|
|
21
|
+
→ gate error → 502 (fail closed)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Protected routes are declared in `agentsafe-routes.json` (path patterns: `*` = one segment, `**` =
|
|
25
|
+
the rest). The route **pins the governed action**, so a client cannot relabel a purchase as a cheap
|
|
26
|
+
read. The agent presents its signed MAGP request in the `x-magp-request` header (the same object the
|
|
27
|
+
guard already verifies); the gateway forwards only on `allow`/`observe`.
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
[
|
|
31
|
+
{ "method": "POST", "path": "/book/*", "action": "flight-purchase" },
|
|
32
|
+
{ "method": "POST", "path": "/payments/**", "action": "payment-execute" }
|
|
33
|
+
]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Run
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
AGENTSAFE_UPSTREAM=https://api.example.com \
|
|
40
|
+
MAGP_API=https://metamynd.ai/api/v1 \
|
|
41
|
+
SERVICE_DID=did:hedera:testnet:... SERVICE_KEY=<hex> \
|
|
42
|
+
AGENTSAFE_ROUTES=agentsafe-routes.json \
|
|
43
|
+
node server.mjs # listens on PORT (default 4000)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`denyByDefault: true` (in `createHttpGateway`) switches to an **allow-list** posture — an unmatched
|
|
47
|
+
route is blocked (`ROUTE_NOT_ALLOWED`) instead of forwarded.
|
|
48
|
+
|
|
49
|
+
## Embed the core
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
import { createHttpGateway } from '@metamynd/agentsafe-http-gateway';
|
|
53
|
+
const handle = createHttpGateway({ guard, routes, forward }); // forward(req) → upstream
|
|
54
|
+
const result = await handle({ method, path, headers, body }); // { status, body, governance? }
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Self-check: `node gateway.smoke.mjs` (route matching, pass-through, allow→forward, block→403,
|
|
58
|
+
missing-governance→401, fail-closed, action-pinning, allow-list posture).
|
package/gateway.mjs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// gateway.mjs — the generic HTTP interception gateway (SAFR §17, Phase-5 PR-4). A reverse proxy
|
|
2
|
+
// that GOVERNS arbitrary HTTP calls (not just MCP): matched protected routes are re-evaluated
|
|
3
|
+
// through the guard before the request is forwarded upstream; everything else passes through.
|
|
4
|
+
//
|
|
5
|
+
// This is the framework-agnostic CORE — a pure-ish request handler with the guard + the upstream
|
|
6
|
+
// forwarder INJECTED, so it is testable with fakes. `server.mjs` binds it to node:http + fetch.
|
|
7
|
+
//
|
|
8
|
+
// A protected route: { method, path, action, extract? }. The gateway needs the agent's SIGNED
|
|
9
|
+
// MAGP request to govern the call — by default it reads header `x-magp-request` (JSON of
|
|
10
|
+
// { agentDid, amount, merchant, itinerary, nonce, issuedAt, signature }); a route may override
|
|
11
|
+
// with its own `extract(req)`. The route's `action` is authoritative (the client can't pick it).
|
|
12
|
+
|
|
13
|
+
import { matchRoute } from './route-match.mjs';
|
|
14
|
+
|
|
15
|
+
/** Default extractor: parse the signed MAGP request from the `x-magp-request` header (JSON). */
|
|
16
|
+
export function defaultExtractGovernance(req) {
|
|
17
|
+
const raw = req.headers?.['x-magp-request'] ?? req.headers?.['X-MAGP-Request'];
|
|
18
|
+
if (!raw) return null;
|
|
19
|
+
try {
|
|
20
|
+
return typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Build the governed request handler.
|
|
28
|
+
* guard — anything with `verifyRequest(signed) => { decision, reasonCode, ... }` (an MCP guard).
|
|
29
|
+
* routes — protected-route configs (see matchRoute). No match ⇒ pass through (unless denyByDefault).
|
|
30
|
+
* forward — async (req) => { status, headers, body }: performs the upstream call. Injected for tests.
|
|
31
|
+
* extractGovernance — override the signed-request extractor (default: x-magp-request header).
|
|
32
|
+
* denyByDefault — when true, an UNMATCHED route is blocked (allow-list posture) instead of forwarded.
|
|
33
|
+
*
|
|
34
|
+
* Returns async (req) => { status, headers?, body, governance? }, where req is a normalized
|
|
35
|
+
* { method, path, headers, body }.
|
|
36
|
+
*/
|
|
37
|
+
export function createHttpGateway({ guard, routes = [], forward, extractGovernance = defaultExtractGovernance, denyByDefault = false } = {}) {
|
|
38
|
+
if (typeof forward !== 'function') throw new Error('createHttpGateway requires a forward(req) function');
|
|
39
|
+
|
|
40
|
+
return async function handle(req) {
|
|
41
|
+
const route = matchRoute(routes, req.method, req.path);
|
|
42
|
+
|
|
43
|
+
// Unprotected route → pass through (or fail closed under an allow-list posture).
|
|
44
|
+
if (!route) {
|
|
45
|
+
if (denyByDefault) {
|
|
46
|
+
return { status: 403, body: { decision: 'block', reasonCode: 'ROUTE_NOT_ALLOWED', path: req.path } };
|
|
47
|
+
}
|
|
48
|
+
return forward(req);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Protected route → the caller must present a signed MAGP request to be governed.
|
|
52
|
+
const signed = (route.extract ?? extractGovernance)(req);
|
|
53
|
+
if (!signed) {
|
|
54
|
+
return { status: 401, body: { decision: 'block', reasonCode: 'MISSING_GOVERNANCE', action: route.action } };
|
|
55
|
+
}
|
|
56
|
+
// The route pins the action — a client cannot relabel a governed call as something cheaper.
|
|
57
|
+
const request = { ...signed, action: route.action ?? signed.action };
|
|
58
|
+
|
|
59
|
+
let decision;
|
|
60
|
+
try {
|
|
61
|
+
decision = await guard.verifyRequest(request);
|
|
62
|
+
} catch (err) {
|
|
63
|
+
// Fail CLOSED: a governance error blocks the upstream call.
|
|
64
|
+
return { status: 502, body: { decision: 'block', reasonCode: 'GOVERNANCE_ERROR', error: String(err?.message ?? err) } };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// allow + observe both PERMIT the upstream call (observe = permit-but-flag, SAFR §11).
|
|
68
|
+
if (decision?.decision !== 'allow' && decision?.decision !== 'observe') {
|
|
69
|
+
return { status: 403, body: { decision: decision?.decision ?? 'block', reasonCode: decision?.reasonCode ?? 'BLOCKED' }, governance: decision };
|
|
70
|
+
}
|
|
71
|
+
const upstream = await forward(req);
|
|
72
|
+
return { ...upstream, governance: decision };
|
|
73
|
+
};
|
|
74
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@metamynd/agentsafe-http-gateway",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Generic HTTP interception gateway (SAFR §17) — a zero-dependency reverse proxy that governs arbitrary HTTP calls through the AgentSafe gate before forwarding upstream.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "gateway.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./gateway.mjs",
|
|
9
|
+
"./route-match": "./route-match.mjs",
|
|
10
|
+
"./server": "./server.mjs",
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"gateway.mjs",
|
|
15
|
+
"route-match.mjs",
|
|
16
|
+
"server.mjs",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"start": "node server.mjs",
|
|
22
|
+
"test": "node gateway.smoke.mjs"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@metamynd/agentsafe-mcp-guard": "^0.1.0"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"sideEffects": false,
|
|
31
|
+
"keywords": [
|
|
32
|
+
"http",
|
|
33
|
+
"gateway",
|
|
34
|
+
"reverse-proxy",
|
|
35
|
+
"ai",
|
|
36
|
+
"agent",
|
|
37
|
+
"agents",
|
|
38
|
+
"governance",
|
|
39
|
+
"authorization",
|
|
40
|
+
"trustless",
|
|
41
|
+
"zero-trust",
|
|
42
|
+
"magp",
|
|
43
|
+
"metamynd",
|
|
44
|
+
"agentsafe"
|
|
45
|
+
],
|
|
46
|
+
"author": "MetaMynd",
|
|
47
|
+
"license": "MIT",
|
|
48
|
+
"homepage": "https://metamynd.ai/en/developers/spec",
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/Metamynd/agentsafe-guard.git",
|
|
52
|
+
"directory": "packages/agentsafe-http-gateway"
|
|
53
|
+
},
|
|
54
|
+
"bugs": {
|
|
55
|
+
"url": "https://github.com/Metamynd/agentsafe-guard/issues"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
}
|
|
60
|
+
}
|
package/route-match.mjs
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// route-match.mjs — pure protected-route matching for the generic HTTP interception gateway
|
|
2
|
+
// (SAFR §17, Phase-5 PR-4). No IO, so the matching rules are deterministic + unit-testable.
|
|
3
|
+
//
|
|
4
|
+
// A protected route is { method, path, action, ... }. `method` is case-insensitive ('*' = any).
|
|
5
|
+
// `path` is a pattern where a `*` matches EXACTLY ONE segment and a trailing `**` matches the rest
|
|
6
|
+
// (one-or-more segments) — enough to express "/book/*", "/api/**", "/quote". An exact path with no
|
|
7
|
+
// wildcard matches only itself.
|
|
8
|
+
|
|
9
|
+
/** Split a URL path into non-empty segments (ignoring query + trailing slash). */
|
|
10
|
+
export function segments(path) {
|
|
11
|
+
const p = String(path || '').split('?')[0];
|
|
12
|
+
return p.split('/').filter(Boolean);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether `path` matches `pattern`. `*` matches exactly one segment; a trailing `**` matches
|
|
17
|
+
* one-or-more remaining segments. Otherwise segments must match 1:1 (and the lengths must be equal).
|
|
18
|
+
*/
|
|
19
|
+
export function pathMatches(pattern, path) {
|
|
20
|
+
const pat = segments(pattern);
|
|
21
|
+
const seg = segments(path);
|
|
22
|
+
for (let i = 0; i < pat.length; i++) {
|
|
23
|
+
const token = pat[i];
|
|
24
|
+
if (token === '**') return seg.length >= pat.length; // tail wildcard: absorb the rest (≥1 segment)
|
|
25
|
+
if (seg[i] === undefined) return false;
|
|
26
|
+
if (token === '*') continue; // single-segment wildcard
|
|
27
|
+
if (token !== seg[i]) return false;
|
|
28
|
+
}
|
|
29
|
+
return seg.length === pat.length; // exact length unless a tail wildcard consumed the remainder
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Whether a route's method matches the request method ('*' or absent = any). */
|
|
33
|
+
export function methodMatches(routeMethod, reqMethod) {
|
|
34
|
+
if (!routeMethod || routeMethod === '*') return true;
|
|
35
|
+
return String(routeMethod).toUpperCase() === String(reqMethod || '').toUpperCase();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The first protected route matching (method, path), or null. Order matters — put more specific
|
|
40
|
+
* routes first. A matched route tells the gateway to GOVERN the request; no match ⇒ pass through.
|
|
41
|
+
*/
|
|
42
|
+
export function matchRoute(routes, method, path) {
|
|
43
|
+
for (const r of routes || []) {
|
|
44
|
+
if (methodMatches(r.method, method) && pathMatches(r.path, path)) return r;
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
package/server.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// server.mjs — binds the generic HTTP interception gateway (SAFR §17, Phase-5 PR-4) to node:http
|
|
2
|
+
// with a fetch-based upstream forwarder + an MCP guard. ZERO external dependencies (node:http +
|
|
3
|
+
// built-in fetch + the zero-dep agentsafe-mcp-guard). Protected routes are re-evaluated through the
|
|
4
|
+
// guard before proxying; everything else passes through to the upstream service unchanged.
|
|
5
|
+
//
|
|
6
|
+
// AGENTSAFE_UPSTREAM=https://api.example.com \
|
|
7
|
+
// MAGP_API=https://metamynd.ai/api/v1 SERVICE_DID=did:hedera:... SERVICE_KEY=<hex> \
|
|
8
|
+
// node server.mjs
|
|
9
|
+
//
|
|
10
|
+
// Protected routes are declared in agentsafe-routes.json (or AGENTSAFE_ROUTES path):
|
|
11
|
+
// [{ "method": "POST", "path": "/book/*", "action": "flight-purchase" }]
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import { readFileSync } from 'node:fs';
|
|
14
|
+
import { createMcpGuard } from '@metamynd/agentsafe-mcp-guard';
|
|
15
|
+
import { createHttpGateway } from './gateway.mjs';
|
|
16
|
+
|
|
17
|
+
const UPSTREAM = (process.env.AGENTSAFE_UPSTREAM || '').replace(/\/$/, '');
|
|
18
|
+
const PORT = Number(process.env.PORT || 4000);
|
|
19
|
+
const MAGP_API = process.env.MAGP_API || 'http://localhost:9926/api/v1';
|
|
20
|
+
const ROUTES_PATH = process.env.AGENTSAFE_ROUTES || 'agentsafe-routes.json';
|
|
21
|
+
|
|
22
|
+
function loadRoutes() {
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(readFileSync(ROUTES_PATH, 'utf8'));
|
|
25
|
+
} catch {
|
|
26
|
+
console.warn(`[gateway] no routes file at ${ROUTES_PATH} — nothing is governed (all pass through)`);
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Read the raw request body (bounded) as a Buffer. */
|
|
32
|
+
function readBody(req) {
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const chunks = [];
|
|
35
|
+
let size = 0;
|
|
36
|
+
req.on('data', (c) => {
|
|
37
|
+
size += c.length;
|
|
38
|
+
if (size > 5 * 1024 * 1024) reject(new Error('body too large'));
|
|
39
|
+
else chunks.push(c);
|
|
40
|
+
});
|
|
41
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
42
|
+
req.on('error', reject);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** fetch-based forwarder to the configured upstream (preserves method, path, headers, body). */
|
|
47
|
+
async function forwardToUpstream(req) {
|
|
48
|
+
if (!UPSTREAM) return { status: 502, body: { error: 'no AGENTSAFE_UPSTREAM configured' } };
|
|
49
|
+
const url = UPSTREAM + req.path;
|
|
50
|
+
const headers = { ...req.headers };
|
|
51
|
+
delete headers.host; // let fetch set the upstream host
|
|
52
|
+
const init = { method: req.method, headers };
|
|
53
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && req.rawBody?.length) init.body = req.rawBody;
|
|
54
|
+
const r = await fetch(url, init);
|
|
55
|
+
const buf = Buffer.from(await r.arrayBuffer());
|
|
56
|
+
const out = {};
|
|
57
|
+
r.headers.forEach((v, k) => (out[k] = v));
|
|
58
|
+
return { status: r.status, headers: out, rawBody: buf };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function main() {
|
|
62
|
+
const guard = createMcpGuard({ serviceDid: process.env.SERVICE_DID, serviceKey: process.env.SERVICE_KEY, issuerApi: MAGP_API });
|
|
63
|
+
const routes = loadRoutes();
|
|
64
|
+
const gateway = createHttpGateway({ guard, routes, forward: forwardToUpstream });
|
|
65
|
+
|
|
66
|
+
const server = http.createServer(async (req, res) => {
|
|
67
|
+
try {
|
|
68
|
+
const rawBody = await readBody(req);
|
|
69
|
+
const normalized = { method: req.method, path: req.url, headers: req.headers, rawBody, body: null };
|
|
70
|
+
const result = await gateway(normalized);
|
|
71
|
+
const headers = result.headers ?? { 'content-type': 'application/json' };
|
|
72
|
+
if (result.governance) headers['x-agentsafe-decision'] = result.governance.decision;
|
|
73
|
+
res.writeHead(result.status, headers);
|
|
74
|
+
if (result.rawBody) res.end(result.rawBody);
|
|
75
|
+
else res.end(typeof result.body === 'string' ? result.body : JSON.stringify(result.body ?? {}));
|
|
76
|
+
} catch (err) {
|
|
77
|
+
// Fail CLOSED on any gateway error.
|
|
78
|
+
res.writeHead(502, { 'content-type': 'application/json' });
|
|
79
|
+
res.end(JSON.stringify({ decision: 'block', reasonCode: 'GATEWAY_ERROR', error: String(err?.message ?? err) }));
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
server.listen(PORT, () => {
|
|
84
|
+
console.log(`[gateway] AgentSafe HTTP interception gateway on :${PORT} → upstream ${UPSTREAM || '(none)'} (${routes.length} protected route(s))`);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
main().catch((e) => { console.error('[gateway] fatal', e); process.exit(1); });
|