passcontrol 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/cli/config.mjs ADDED
@@ -0,0 +1,237 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const CONFIG_FILE = ".passcontrol";
6
+ export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together", "deepseek"];
7
+ export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek"]);
8
+
9
+ const DEFAULT_GATEWAY = "http://localhost:3000";
10
+ const DEFAULT_PROVIDER = "anthropic";
11
+ const CONFIG_KEYS = [
12
+ "PASSCONTROL_GATEWAY",
13
+ "PASSPORT_ID",
14
+ "PASSPORT_SECRET",
15
+ "PASSCONTROL_API_KEY",
16
+ "PROVIDER",
17
+ "MODEL",
18
+ ];
19
+
20
+ const trimSlash = (value) => String(value ?? "").replace(/\/+$/, "");
21
+
22
+ export function defaultModelForProvider(provider) {
23
+ switch (provider) {
24
+ case "openai":
25
+ return "gpt-4o-mini";
26
+ case "groq":
27
+ return "llama-3.1-8b-instant";
28
+ case "mistral":
29
+ return "mistral-small-latest";
30
+ case "together":
31
+ return "openai/gpt-oss-20b";
32
+ case "deepseek":
33
+ return "deepseek-chat";
34
+ case "anthropic":
35
+ default:
36
+ return "claude-haiku-4-5";
37
+ }
38
+ }
39
+
40
+ function unquote(value) {
41
+ if (
42
+ (value.startsWith('"') && value.endsWith('"')) ||
43
+ (value.startsWith("'") && value.endsWith("'"))
44
+ ) {
45
+ return value.slice(1, -1);
46
+ }
47
+ return value;
48
+ }
49
+
50
+ export function parseDotenv(text, source = CONFIG_FILE) {
51
+ const values = {};
52
+ for (const [i, rawLine] of text.split(/\r?\n/).entries()) {
53
+ const trimmed = rawLine.trim();
54
+ if (!trimmed || trimmed.startsWith("#")) continue;
55
+
56
+ const line = trimmed.startsWith("export ") ? trimmed.slice("export ".length).trim() : trimmed;
57
+ const eq = line.indexOf("=");
58
+ if (eq === -1) throw new Error(`Invalid ${source} line ${i + 1}: expected KEY=value.`);
59
+
60
+ const key = line.slice(0, eq).trim();
61
+ const value = unquote(line.slice(eq + 1).trim());
62
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
63
+ throw new Error(`Invalid ${source} line ${i + 1}: bad env var name "${key}".`);
64
+ }
65
+ values[key] = value;
66
+ }
67
+ return values;
68
+ }
69
+
70
+ function readConfigFile(file) {
71
+ return parseDotenv(fs.readFileSync(file, "utf8"), file);
72
+ }
73
+
74
+ export function globalConfigPath(env = process.env) {
75
+ const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
76
+ return path.join(base, "passcontrol", "config");
77
+ }
78
+
79
+ export function findProjectConfig(start = process.cwd()) {
80
+ let dir = path.resolve(start);
81
+ for (;;) {
82
+ const candidate = path.join(dir, CONFIG_FILE);
83
+ if (fs.existsSync(candidate)) return candidate;
84
+
85
+ const parent = path.dirname(dir);
86
+ if (parent === dir) return null;
87
+ dir = parent;
88
+ }
89
+ }
90
+
91
+ export function loadConfigSources({ cwd = process.cwd(), env = process.env } = {}) {
92
+ const sources = [];
93
+ const globalPath = globalConfigPath(env);
94
+ const projectPath = findProjectConfig(cwd);
95
+
96
+ if (fs.existsSync(globalPath)) {
97
+ sources.push({ type: "global", path: globalPath, values: readConfigFile(globalPath) });
98
+ }
99
+ if (projectPath) {
100
+ sources.push({ type: "project", path: projectPath, values: readConfigFile(projectPath) });
101
+ }
102
+ return sources;
103
+ }
104
+
105
+ export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env } = {}) {
106
+ const sources = loadConfigSources({ cwd, env });
107
+ const merged = {};
108
+ for (const source of sources) Object.assign(merged, source.values);
109
+ for (const [key, value] of Object.entries(merged)) {
110
+ if (env[key] === undefined) env[key] = value;
111
+ }
112
+ return sources;
113
+ }
114
+
115
+ export let configLoadError = null;
116
+ export let configSources = [];
117
+
118
+ try {
119
+ configSources = applyConfigSourcesToEnv();
120
+ } catch (error) {
121
+ configLoadError = error;
122
+ }
123
+
124
+ export function assertConfigLoaded() {
125
+ if (configLoadError) throw configLoadError;
126
+ }
127
+
128
+ export function resolveModel(provider) {
129
+ return process.env.MODEL ?? defaultModelForProvider(provider);
130
+ }
131
+
132
+ export function resolvedConfig() {
133
+ assertConfigLoaded();
134
+ return currentConfig();
135
+ }
136
+
137
+ function currentConfig() {
138
+ const provider = process.env.PROVIDER ?? DEFAULT_PROVIDER;
139
+ return {
140
+ gateway: trimSlash(process.env.PASSCONTROL_GATEWAY ?? DEFAULT_GATEWAY),
141
+ passportId: process.env.PASSPORT_ID ?? "",
142
+ passportSecret: process.env.PASSPORT_SECRET ?? "",
143
+ apiKey: process.env.PASSCONTROL_API_KEY ?? "",
144
+ provider,
145
+ model: resolveModel(provider),
146
+ sources: configSources,
147
+ };
148
+ }
149
+
150
+ export const config = currentConfig();
151
+
152
+ export function configPathLabel(sources = configSources) {
153
+ const project = sources.find((source) => source.type === "project");
154
+ const global = sources.find((source) => source.type === "global");
155
+ if (project) return project.path;
156
+ if (global) return global.path;
157
+ return "none";
158
+ }
159
+
160
+ export function writeConfigFile(file, values) {
161
+ fs.mkdirSync(path.dirname(file), { recursive: true });
162
+ const lines = [
163
+ "# PassControl CLI config.",
164
+ "# Keep this file private: it can contain a passport secret.",
165
+ "",
166
+ ];
167
+ for (const key of CONFIG_KEYS) {
168
+ lines.push(`${key}=${values[key] ?? ""}`);
169
+ }
170
+ fs.writeFileSync(file, `${lines.join("\n")}\n`, { mode: 0o600 });
171
+ }
172
+
173
+ export function step(message = "") {
174
+ console.log(`→ ${message}`);
175
+ }
176
+
177
+ export function ok(message = "") {
178
+ console.log(`✓ ${message}`);
179
+ }
180
+
181
+ export function fail(message = "") {
182
+ console.error(`✗ ${message}`);
183
+ }
184
+
185
+ export function die(message) {
186
+ fail(message);
187
+ process.exit(1);
188
+ }
189
+
190
+ export function requirePassport(current = config) {
191
+ assertConfigLoaded();
192
+ if (!current.passportId || !current.passportSecret) {
193
+ die(
194
+ "No passport configured. Run `passcontrol init`, copy .passcontrol.example to .passcontrol, or pass PASSPORT_ID/PASSPORT_SECRET as env."
195
+ );
196
+ }
197
+ return { passportId: current.passportId, passportSecret: current.passportSecret };
198
+ }
199
+
200
+ export function requireControlApiKey(current = config) {
201
+ assertConfigLoaded();
202
+ if (!current.apiKey) {
203
+ die(
204
+ "No control-plane API key configured. Run `passcontrol init`, set PASSCONTROL_API_KEY in .passcontrol, or pass it as env."
205
+ );
206
+ }
207
+ return current.apiKey;
208
+ }
209
+
210
+ export function redact(value, keep = 4) {
211
+ if (!value) return "missing";
212
+ const s = String(value);
213
+ if (s.length <= keep) return "configured";
214
+ return `configured (...${s.slice(-keep)})`;
215
+ }
216
+
217
+ export function formatChallengeError(status, body) {
218
+ const detail = String(body ?? "").trim();
219
+ if (status === 403 && detail.includes("agent_not_active")) {
220
+ return "Challenge failed: this agent is suspended or revoked. Re-enable it in the dashboard, or run `passcontrol agent resume <id>`.";
221
+ }
222
+ if (status === 401) {
223
+ return `Challenge failed: 401 ${detail}. Check PASSPORT_ID/PASSPORT_SECRET, then retry.`;
224
+ }
225
+ return `Challenge failed: ${status} ${detail}`;
226
+ }
227
+
228
+ export function formatProxyError(status, body) {
229
+ const detail = String(body ?? "").trim();
230
+ if (status === 402) {
231
+ return `Proxy blocked the call with 402: ${detail}\n→ Fix: raise or clear the agent budget in the dashboard, then retry.`;
232
+ }
233
+ if (status === 403) {
234
+ return `Proxy blocked the call with 403: ${detail}\n→ Fix: check the agent scope, suspend/revoke state, and kill switch.`;
235
+ }
236
+ return `Proxy error ${status}: ${detail}`;
237
+ }
@@ -0,0 +1,111 @@
1
+ import http from "node:http";
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"));
9
+
10
+ const STRIP_REQ = new Set(["authorization", "x-api-key", "host", "content-length", "accept-encoding", "connection"]);
11
+ const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
12
+
13
+ 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
+ }
46
+
47
+ function readBody(req) {
48
+ return new Promise((resolve, reject) => {
49
+ const chunks = [];
50
+ req.on("data", (c) => chunks.push(c));
51
+ req.on("end", () => resolve(chunks.length ? Buffer.concat(chunks) : undefined));
52
+ req.on("error", reject);
53
+ });
54
+ }
55
+
56
+ async function fetchUpstream(req, body, visa) {
57
+ const headers = {};
58
+ for (const [k, v] of Object.entries(req.headers)) {
59
+ if (!STRIP_REQ.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
60
+ }
61
+ headers["authorization"] = `Bearer ${visa}`;
62
+ headers["accept-encoding"] = "identity";
63
+ return fetch(`${gateway}${req.url}`, { method: req.method, headers, body: body ?? undefined });
64
+ }
65
+
66
+ function writeResponse(res, upstream) {
67
+ const outHeaders = {};
68
+ upstream.headers.forEach((v, k) => {
69
+ if (!STRIP_RES.has(k.toLowerCase())) outHeaders[k] = v;
70
+ });
71
+ res.writeHead(upstream.status, outHeaders);
72
+ if (upstream.body) Readable.fromWeb(upstream.body).pipe(res);
73
+ else res.end();
74
+ }
75
+
76
+ const server = http.createServer(async (req, res) => {
77
+ try {
78
+ 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
+ }
84
+ writeResponse(res, upstream);
85
+ } catch (e) {
86
+ if (!res.headersSent) {
87
+ res.writeHead(502, { "content-type": "application/json" });
88
+ res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
89
+ } else {
90
+ res.end();
91
+ }
92
+ }
93
+ });
94
+
95
+ return { server, getVisa };
96
+ }
97
+
98
+ export function startSidecar(opts) {
99
+ const { gateway, port = 8788, host = "127.0.0.1" } = opts;
100
+ const { server, getVisa } = createSidecar(opts);
101
+ server.listen(port, host, () => {
102
+ step(`PassControl visa sidecar forwarding to ${gateway}`);
103
+ step(`Listening on http://${host}:${port}`);
104
+ step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
105
+ step("API key = anything (ignored). Visa is minted + refreshed automatically.\n");
106
+ getVisa()
107
+ .then(() => ok("visa warmed"))
108
+ .catch((e) => fail(`could not mint initial visa: ${e.message}`));
109
+ });
110
+ return server;
111
+ }
package/package.json ADDED
@@ -0,0 +1,88 @@
1
+ {
2
+ "name": "passcontrol",
3
+ "version": "0.1.0",
4
+ "description": "Secure Agent Control Plane & Passport Vault — identity-aware reverse proxy for AI agent credentials.",
5
+ "license": "BUSL-1.1",
6
+ "homepage": "https://github.com/Vertias3u/PassControl#readme",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Vertias3u/PassControl.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/Vertias3u/PassControl/issues"
13
+ },
14
+ "keywords": [
15
+ "ai",
16
+ "agents",
17
+ "llm",
18
+ "gateway",
19
+ "credentials",
20
+ "identity",
21
+ "api-key",
22
+ "vault",
23
+ "proxy",
24
+ "passport"
25
+ ],
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "bin",
34
+ "cli",
35
+ "LICENSE",
36
+ "README.md"
37
+ ],
38
+ "bin": {
39
+ "passcontrol": "bin/passcontrol.mjs"
40
+ },
41
+ "scripts": {
42
+ "cli": "node bin/passcontrol.mjs",
43
+ "dev": "next dev",
44
+ "build": "next build",
45
+ "start": "next start",
46
+ "lint": "next lint",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run",
49
+ "migrate": "bash scripts/migrate.sh",
50
+ "dev:stack": "bash scripts/dev-stack.sh",
51
+ "dev:docker": "bash -c 'set -a; . ./.env.docker; set +a; next dev'",
52
+ "seed": "node scripts/seed.mjs",
53
+ "sidecar": "node examples/visa-sidecar.mjs",
54
+ "test:rls": "psql -v ON_ERROR_STOP=1 -f db/tests/rls_invariants.sql \"$DATABASE_URL\"",
55
+ "check:npm-pack": "node scripts/check-npm-package.mjs",
56
+ "prepare": "git config core.hooksPath .githooks || true"
57
+ },
58
+ "dependencies": {
59
+ "@base-ui/react": "^1.5.0",
60
+ "@noble/curves": "^1.6.0",
61
+ "@noble/hashes": "^1.5.0",
62
+ "@sentry/nextjs": "^10.64.0",
63
+ "@supabase/ssr": "^0.5.1",
64
+ "@supabase/supabase-js": "^2.45.4",
65
+ "@upstash/redis": "^1.34.0",
66
+ "@vercel/functions": "^1.4.0",
67
+ "class-variance-authority": "^0.7.1",
68
+ "clsx": "^2.1.1",
69
+ "jose": "^5.9.3",
70
+ "lucide-react": "^1.20.0",
71
+ "next": "^15.0.0",
72
+ "react": "^18.3.1",
73
+ "react-dom": "^18.3.1",
74
+ "shadcn": "^4.11.0",
75
+ "tailwind-merge": "^3.6.0",
76
+ "tw-animate-css": "^1.4.0"
77
+ },
78
+ "devDependencies": {
79
+ "@tailwindcss/postcss": "^4.3.1",
80
+ "@types/node": "^22.5.5",
81
+ "@types/react": "^18.3.8",
82
+ "@types/react-dom": "^18.3.0",
83
+ "postcss": "^8.5.15",
84
+ "tailwindcss": "^4.3.1",
85
+ "typescript": "^5.6.2",
86
+ "vitest": "^4.1.9"
87
+ }
88
+ }