passcontrol 0.1.2 → 0.3.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.
@@ -0,0 +1,96 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+
6
+ export const MCP_INTEGRATIONS = new Set(["claude-desktop", "cursor", "claude-code"]);
7
+ export const CLAUDE_CODE_ADD_COMMAND =
8
+ "claude mcp add --scope user passcontrol -- passcontrol mcp";
9
+
10
+ export function isMcpIntegration(name) {
11
+ return MCP_INTEGRATIONS.has(name);
12
+ }
13
+
14
+ export function mcpServerEntry({ cliPath, nodePath = process.execPath }) {
15
+ return {
16
+ command: path.resolve(nodePath),
17
+ args: [path.resolve(cliPath), "mcp"],
18
+ };
19
+ }
20
+
21
+ export function mcpServersDocument(entry) {
22
+ return { mcpServers: { passcontrol: entry } };
23
+ }
24
+
25
+ export function mcpClientConfigPath(
26
+ integration,
27
+ { platform = process.platform, home = os.homedir(), env = process.env } = {}
28
+ ) {
29
+ if (integration === "cursor") return path.join(home, ".cursor", "mcp.json");
30
+ if (integration !== "claude-desktop") return null;
31
+
32
+ if (platform === "darwin") {
33
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
34
+ }
35
+ if (platform === "win32") {
36
+ const appData = env.APPDATA || path.join(home, "AppData", "Roaming");
37
+ return path.join(appData, "Claude", "claude_desktop_config.json");
38
+ }
39
+ const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
40
+ return path.join(configHome, "Claude", "claude_desktop_config.json");
41
+ }
42
+
43
+ function readConfigObject(target) {
44
+ if (!fs.existsSync(target)) return { exists: false, value: {} };
45
+
46
+ let value;
47
+ try {
48
+ value = JSON.parse(fs.readFileSync(target, "utf8"));
49
+ } catch (error) {
50
+ throw new Error(`Cannot parse ${target}: ${error.message}`);
51
+ }
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
53
+ throw new Error(`${target} must contain a JSON object.`);
54
+ }
55
+ if (
56
+ value.mcpServers !== undefined &&
57
+ (!value.mcpServers || typeof value.mcpServers !== "object" || Array.isArray(value.mcpServers))
58
+ ) {
59
+ throw new Error(`${target} has an invalid mcpServers value; expected a JSON object.`);
60
+ }
61
+ return { exists: true, value };
62
+ }
63
+
64
+ export function writeMcpClientConfig({ target, entry, force = false }) {
65
+ const { exists, value } = readConfigObject(target);
66
+ const mcpServers = value.mcpServers ?? {};
67
+ const hasPassControl = Object.prototype.hasOwnProperty.call(mcpServers, "passcontrol");
68
+ if (hasPassControl && !isDeepStrictEqual(mcpServers.passcontrol, entry) && !force) {
69
+ throw new Error(
70
+ `${target} already has a different mcpServers.passcontrol entry; re-run with --force to replace only that entry.`
71
+ );
72
+ }
73
+ if (hasPassControl && isDeepStrictEqual(mcpServers.passcontrol, entry)) {
74
+ return { changed: false, backupPath: null };
75
+ }
76
+
77
+ const merged = {
78
+ ...value,
79
+ mcpServers: {
80
+ ...mcpServers,
81
+ passcontrol: entry,
82
+ },
83
+ };
84
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
85
+
86
+ let backupPath = null;
87
+ if (exists) {
88
+ backupPath = `${target}.bak`;
89
+ fs.copyFileSync(target, backupPath);
90
+ fs.chmodSync(backupPath, 0o600);
91
+ }
92
+
93
+ fs.writeFileSync(target, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600 });
94
+ fs.chmodSync(target, 0o600);
95
+ return { changed: true, backupPath };
96
+ }
@@ -0,0 +1,114 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod/v4";
4
+ import { PROVIDERS } from "../config.mjs";
5
+ import { createGatewayClient } from "./gateway.mjs";
6
+
7
+ const messageSchema = z.object({
8
+ role: z.enum(["system", "user", "assistant"]),
9
+ content: z.string().min(1),
10
+ });
11
+
12
+ const usageSchema = z.record(z.string(), z.unknown());
13
+ const modelSchema = z.object({
14
+ provider: z.string(),
15
+ model: z.string(),
16
+ });
17
+
18
+ function toolError(error) {
19
+ return {
20
+ content: [
21
+ {
22
+ type: "text",
23
+ text: error instanceof Error ? error.message : String(error),
24
+ },
25
+ ],
26
+ isError: true,
27
+ };
28
+ }
29
+
30
+ export function createMcpServer(options) {
31
+ const gateway = createGatewayClient(options);
32
+ const server = new McpServer(
33
+ { name: "passcontrol", version: "0.2.0" },
34
+ {
35
+ instructions:
36
+ "Use chat for governed model calls through PassControl. Every chat call is subject to the configured passport's scope, budget, and kill switches.",
37
+ }
38
+ );
39
+
40
+ server.registerTool(
41
+ "chat",
42
+ {
43
+ title: "Governed model chat",
44
+ description:
45
+ "Call a supported model through the PassControl gateway. The provider key stays in the gateway; passport scope, budget, and kill switches apply.",
46
+ inputSchema: {
47
+ provider: z.enum(PROVIDERS),
48
+ model: z.string().min(1),
49
+ messages: z.array(messageSchema).min(1),
50
+ max_tokens: z.number().int().positive().optional(),
51
+ temperature: z.number().min(0).max(2).optional(),
52
+ },
53
+ outputSchema: {
54
+ text: z.string(),
55
+ usage: usageSchema.optional(),
56
+ },
57
+ annotations: {
58
+ destructiveHint: false,
59
+ idempotentHint: false,
60
+ openWorldHint: true,
61
+ },
62
+ },
63
+ async (input) => {
64
+ try {
65
+ const result = await gateway.chat(input);
66
+ const structuredContent = {
67
+ text: result.text,
68
+ ...(result.usage ? { usage: result.usage } : {}),
69
+ };
70
+ return {
71
+ content: [{ type: "text", text: result.text }],
72
+ structuredContent,
73
+ };
74
+ } catch (error) {
75
+ return toolError(error);
76
+ }
77
+ }
78
+ );
79
+
80
+ server.registerTool(
81
+ "list_models",
82
+ {
83
+ title: "List scoped models",
84
+ description:
85
+ "List provider/model patterns in the gateway-issued scope for the configured passport.",
86
+ outputSchema: { models: z.array(modelSchema) },
87
+ annotations: {
88
+ readOnlyHint: true,
89
+ destructiveHint: false,
90
+ idempotentHint: true,
91
+ openWorldHint: false,
92
+ },
93
+ },
94
+ async () => {
95
+ try {
96
+ const structuredContent = { models: await gateway.listModels() };
97
+ return {
98
+ content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }],
99
+ structuredContent,
100
+ };
101
+ } catch (error) {
102
+ return toolError(error);
103
+ }
104
+ }
105
+ );
106
+
107
+ return server;
108
+ }
109
+
110
+ export async function startMcpServer(options) {
111
+ const server = createMcpServer(options);
112
+ await server.connect(new StdioServerTransport());
113
+ return server;
114
+ }
package/cli/sidecar.mjs CHANGED
@@ -1,48 +1,19 @@
1
1
  import http from "node:http";
2
2
  import { Readable } from "node:stream";
3
- import { ed25519 } from "@noble/curves/ed25519";
4
- import { fail, formatChallengeError, ok, step } from "./config.mjs";
5
-
6
- const b64url = (bytes) =>
7
- Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8
- const fromB64url = (s) => new Uint8Array(Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
3
+ import { fail, ok, step } from "./config.mjs";
4
+ import { createVisaClient } from "./visa-client.mjs";
9
5
 
10
6
  const STRIP_REQ = new Set(["authorization", "x-api-key", "host", "content-length", "accept-encoding", "connection"]);
11
7
  const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
12
8
 
13
9
  export function createSidecar({ gateway, passportId, passportSecret, port = 8788, host = "127.0.0.1", refreshSkewSeconds = 30 }) {
14
- const skewMs = Math.max(0, Number(refreshSkewSeconds) * 1000);
15
- let cached = null;
16
- let inflight = null;
17
-
18
- async function mint() {
19
- const obj = { passport_id: passportId, ts: Date.now(), nonce: crypto.randomUUID() };
20
- const payload = b64url(new TextEncoder().encode(JSON.stringify(obj)));
21
- const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
22
- const res = await fetch(`${gateway}/api/auth/challenge`, {
23
- method: "POST",
24
- headers: { "content-type": "application/json" },
25
- body: JSON.stringify({ payload, signature }),
26
- });
27
- if (!res.ok) throw new Error(formatChallengeError(res.status, await res.text()));
28
- const { visa, expires_in } = await res.json();
29
- if (!visa) throw new Error("challenge returned no visa");
30
- return { token: visa, expiresAt: Date.now() + (expires_in ?? 300) * 1000 };
31
- }
32
-
33
- async function getVisa() {
34
- if (cached && Date.now() < cached.expiresAt - skewMs) return cached.token;
35
- if (inflight) return inflight;
36
- inflight = mint()
37
- .then((v) => {
38
- cached = v;
39
- return v.token;
40
- })
41
- .finally(() => {
42
- inflight = null;
43
- });
44
- return inflight;
45
- }
10
+ const visas = createVisaClient({
11
+ gateway,
12
+ passportId,
13
+ passportSecret,
14
+ refreshSkewSeconds,
15
+ missingVisaMessage: "challenge returned no visa",
16
+ });
46
17
 
47
18
  function readBody(req) {
48
19
  return new Promise((resolve, reject) => {
@@ -76,11 +47,7 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
76
47
  const server = http.createServer(async (req, res) => {
77
48
  try {
78
49
  const body = await readBody(req);
79
- let upstream = await fetchUpstream(req, body, await getVisa());
80
- if (upstream.status === 401) {
81
- cached = null;
82
- upstream = await fetchUpstream(req, body, await getVisa());
83
- }
50
+ const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, body, visa));
84
51
  writeResponse(res, upstream);
85
52
  } catch (e) {
86
53
  if (!res.headersSent) {
@@ -92,7 +59,7 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
92
59
  }
93
60
  });
94
61
 
95
- return { server, getVisa };
62
+ return { server, getVisa: visas.getVisa };
96
63
  }
97
64
 
98
65
  export function startSidecar(opts) {
@@ -0,0 +1,74 @@
1
+ import { ed25519 } from "@noble/curves/ed25519";
2
+ import { formatChallengeError } from "./config.mjs";
3
+
4
+ const b64url = (bytes) =>
5
+ Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
6
+ const fromB64url = (value) =>
7
+ new Uint8Array(Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
8
+
9
+ export function createVisaClient({
10
+ gateway,
11
+ passportId,
12
+ passportSecret,
13
+ fetch: fetchImpl = (...args) => globalThis.fetch(...args),
14
+ now = () => Date.now(),
15
+ randomUUID = () => globalThis.crypto.randomUUID(),
16
+ refreshSkewSeconds = 30,
17
+ missingVisaMessage = "Challenge returned no visa.",
18
+ }) {
19
+ const skewMs = Math.max(0, Number(refreshSkewSeconds) * 1000);
20
+ let cached = null;
21
+ let inflight = null;
22
+
23
+ async function mint() {
24
+ const payloadObject = { passport_id: passportId, ts: now(), nonce: randomUUID() };
25
+ const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObject)));
26
+ const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
27
+ const response = await fetchImpl(`${gateway}/api/auth/challenge`, {
28
+ method: "POST",
29
+ headers: { "content-type": "application/json" },
30
+ body: JSON.stringify({ payload, signature }),
31
+ });
32
+
33
+ if (!response.ok) {
34
+ throw new Error(formatChallengeError(response.status, await response.text()));
35
+ }
36
+
37
+ const data = await response.json();
38
+ if (!data.visa) throw new Error(missingVisaMessage);
39
+ return {
40
+ token: data.visa,
41
+ expiresAt: now() + (data.expires_in ?? 300) * 1000,
42
+ };
43
+ }
44
+
45
+ async function getVisa() {
46
+ if (cached && now() < cached.expiresAt - skewMs) return cached.token;
47
+ if (inflight) return inflight;
48
+
49
+ inflight = mint()
50
+ .then((visa) => {
51
+ cached = visa;
52
+ return visa.token;
53
+ })
54
+ .finally(() => {
55
+ inflight = null;
56
+ });
57
+ return inflight;
58
+ }
59
+
60
+ function invalidate() {
61
+ cached = null;
62
+ }
63
+
64
+ async function fetchWithVisa(request) {
65
+ let response = await request(await getVisa());
66
+ if (response.status === 401) {
67
+ invalidate();
68
+ response = await request(await getVisa());
69
+ }
70
+ return response;
71
+ }
72
+
73
+ return { getVisa, invalidate, fetchWithVisa };
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Secure Agent Control Plane & Passport Vault — identity-aware reverse proxy for AI agent credentials.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://github.com/Vertias3u/PassControl#readme",
@@ -32,6 +32,7 @@
32
32
  "files": [
33
33
  "bin",
34
34
  "cli",
35
+ "!cli/**/__tests__",
35
36
  "LICENSE",
36
37
  "README.md"
37
38
  ],
@@ -57,6 +58,7 @@
57
58
  },
58
59
  "dependencies": {
59
60
  "@base-ui/react": "^1.5.0",
61
+ "@modelcontextprotocol/sdk": "^1.29.0",
60
62
  "@noble/curves": "^1.6.0",
61
63
  "@noble/hashes": "^1.5.0",
62
64
  "@sentry/nextjs": "^10.64.0",
@@ -73,7 +75,8 @@
73
75
  "react-dom": "^18.3.1",
74
76
  "shadcn": "^4.11.0",
75
77
  "tailwind-merge": "^3.6.0",
76
- "tw-animate-css": "^1.4.0"
78
+ "tw-animate-css": "^1.4.0",
79
+ "zod": "^3.25.76"
77
80
  },
78
81
  "devDependencies": {
79
82
  "@tailwindcss/postcss": "^4.3.1",