Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 118 additions & 3 deletions connectors/remote/config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,118 @@
export interface RemoteConfig{host:string;port:number;path:string;publicUrl:URL;allowedHosts:Set<string>;allowedOrigins:Set<string>;maxBodyBytes:number;maxRequestsPerMinute:number;trustProxy:boolean}
const csv=(v:string|undefined)=>new Set((v??"").split(",").map(x=>x.trim().toLowerCase()).filter(Boolean));
export function loadRemoteConfig(env=process.env):RemoteConfig{const raw=env.AIFIAR_REMOTE_PUBLIC_URL;if(!raw)throw new Error("AIFIAR_REMOTE_PUBLIC_URL is required.");let publicUrl:URL;try{publicUrl=new URL(raw)}catch{throw new Error("AIFIAR_REMOTE_PUBLIC_URL must be an absolute URL.")}if(publicUrl.protocol!=="https:"||publicUrl.username||publicUrl.password||publicUrl.search||publicUrl.hash)throw new Error("AIFIAR_REMOTE_PUBLIC_URL must be HTTPS and contain no credentials, query, or fragment.");const path=env.AIFIAR_REMOTE_PATH??"/mcp";if(!path.startsWith("/")||path.includes("?")||path.includes("#")||path.includes(".."))throw new Error("AIFIAR_REMOTE_PATH must be a safe absolute path.");if(publicUrl.pathname.replace(/\/$/,"")!==path.replace(/\/$/,""))throw new Error("Public URL path must exactly match AIFIAR_REMOTE_PATH.");const allowedHosts=csv(env.AIFIAR_REMOTE_ALLOWED_HOSTS);allowedHosts.add(publicUrl.host.toLowerCase());const allowedOrigins=csv(env.AIFIAR_REMOTE_ALLOWED_ORIGINS);const port=Number(env.AIFIAR_REMOTE_PORT??8787),maxBodyBytes=Number(env.AIFIAR_REMOTE_MAX_BODY_BYTES??1048576),maxRequestsPerMinute=Number(env.AIFIAR_REMOTE_MAX_REQUESTS_PER_MINUTE??120);if(!Number.isInteger(port)||port<1||port>65535)throw new Error("Remote port must be an integer from 1 to 65535.");if(!Number.isInteger(maxBodyBytes)||maxBodyBytes<1024||maxBodyBytes>10485760)throw new Error("Remote body limit must be 1 KiB to 10 MiB.");if(!Number.isInteger(maxRequestsPerMinute)||maxRequestsPerMinute<1||maxRequestsPerMinute>10000)throw new Error("Remote global rate limit must be 1 to 10000 requests per minute.");return{host:env.AIFIAR_REMOTE_HOST??"127.0.0.1",port,path,publicUrl,allowedHosts,allowedOrigins,maxBodyBytes,maxRequestsPerMinute,trustProxy:false}}
export interface RemoteConfig {
host: string;
port: number;
path: string;
publicUrl: URL;
allowedHosts: Set<string>;
allowedOrigins: Set<string>;
maxBodyBytes: number;
maxRequestsPerMinute: number;
trustProxy: boolean;
}

function parseList(value: string | undefined): string[] {
return (value ?? "").split(",").map(item => item.trim()).filter(Boolean);
}

function parseAllowedHosts(value: string | undefined, publicHost: string): Set<string> {
const hosts = new Set(parseList(value).map(host => host.toLowerCase()));
hosts.add(publicHost.toLowerCase());
for (const host of hosts) {
if (
host === "*" ||
host.includes("/") ||
host.includes("@") ||
host.includes(" ") ||
host.includes("\\")
) throw new Error("AIFIAR_REMOTE_ALLOWED_HOSTS must contain exact host[:port] values.");
let parsed: URL;
try {
parsed = new URL("https://" + host);
} catch {
throw new Error("AIFIAR_REMOTE_ALLOWED_HOSTS contains an invalid host.");
}
if (parsed.host.toLowerCase() !== host || parsed.pathname !== "/" || parsed.search || parsed.hash) {
throw new Error("AIFIAR_REMOTE_ALLOWED_HOSTS must contain exact host[:port] values.");
}
}
return hosts;
}

function parseAllowedOrigins(value: string | undefined): Set<string> {
const origins = new Set<string>();
for (const item of parseList(value)) {
let origin: URL;
try {
origin = new URL(item);
} catch {
throw new Error("AIFIAR_REMOTE_ALLOWED_ORIGINS must contain valid HTTPS origins.");
}
if (
origin.protocol !== "https:" ||
origin.username ||
origin.password ||
origin.pathname !== "/" ||
origin.search ||
origin.hash ||
origin.origin !== item.replace(/\/$/, "")
) throw new Error("AIFIAR_REMOTE_ALLOWED_ORIGINS must contain exact HTTPS origins without paths or credentials.");
origins.add(origin.origin.toLowerCase());
}
return origins;
}

export function loadRemoteConfig(env = process.env): RemoteConfig {
const raw = env.AIFIAR_REMOTE_PUBLIC_URL;
if (!raw) throw new Error("AIFIAR_REMOTE_PUBLIC_URL is required.");

let publicUrl: URL;
try {
publicUrl = new URL(raw);
} catch {
throw new Error("AIFIAR_REMOTE_PUBLIC_URL must be an absolute URL.");
}

if (
publicUrl.protocol !== "https:" ||
publicUrl.username ||
publicUrl.password ||
publicUrl.search ||
publicUrl.hash
) throw new Error("AIFIAR_REMOTE_PUBLIC_URL must be HTTPS and contain no credentials, query, or fragment.");

const path = env.AIFIAR_REMOTE_PATH ?? "/mcp";
if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("..") || path.includes("\\\\")) {
throw new Error("AIFIAR_REMOTE_PATH must be a safe absolute path.");
}
if (publicUrl.pathname.replace(/\/$/, "") !== path.replace(/\/$/, "")) {
throw new Error("Public URL path must exactly match AIFIAR_REMOTE_PATH.");
}

const allowedHosts = parseAllowedHosts(env.AIFIAR_REMOTE_ALLOWED_HOSTS, publicUrl.host);
const allowedOrigins = parseAllowedOrigins(env.AIFIAR_REMOTE_ALLOWED_ORIGINS);
const port = Number(env.AIFIAR_REMOTE_PORT ?? 8787);
const maxBodyBytes = Number(env.AIFIAR_REMOTE_MAX_BODY_BYTES ?? 1048576);
const maxRequestsPerMinute = Number(env.AIFIAR_REMOTE_MAX_REQUESTS_PER_MINUTE ?? 120);

if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("Remote port must be an integer from 1 to 65535.");
}
if (!Number.isInteger(maxBodyBytes) || maxBodyBytes < 1024 || maxBodyBytes > 10485760) {
throw new Error("Remote body limit must be 1 KiB to 10 MiB.");
}
if (!Number.isInteger(maxRequestsPerMinute) || maxRequestsPerMinute < 1 || maxRequestsPerMinute > 10000) {
throw new Error("Remote global rate limit must be 1 to 10000 requests per minute.");
}

return {
host: env.AIFIAR_REMOTE_HOST ?? "127.0.0.1",
port,
path,
publicUrl,
allowedHosts,
allowedOrigins,
maxBodyBytes,
maxRequestsPerMinute,
trustProxy: false
};
}
252 changes: 220 additions & 32 deletions connectors/remote/oidc.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,223 @@
import { createPublicKey, verify as verifySignature } from "node:crypto";
import type { RemotePrincipal } from "./auth.js";
export interface OidcConfig { issuer:string; audience:string; jwksUrl:URL; cacheMs:number }
interface Jwk { kid?:string; kty?:string; use?:string; alg?:string; n?:string; e?:string }
const TOOLS=["aifiar_status","aifiar_list_models","aifiar_get_instructions","aifiar_prepare_repository"];
const PROFILES=["claude","gpt","grok","codex","cursor"];
const isRecord=(v:unknown):v is Record<string,unknown>=>v!==null&&typeof v==="object"&&!Array.isArray(v);
export function loadOidcConfig(env=process.env):OidcConfig|null {
const issuer=env.AIFIAR_OIDC_ISSUER,audience=env.AIFIAR_OIDC_AUDIENCE,jwks=env.AIFIAR_OIDC_JWKS_URL;
if(!issuer&&!audience&&!jwks)return null;
if(!issuer||!audience||!jwks)throw new Error("OIDC requires issuer, audience, and JWKS URL together.");
let i:URL,j:URL;try{i=new URL(issuer);j=new URL(jwks)}catch{throw new Error("OIDC issuer and JWKS URL must be absolute URLs.")}
if(i.protocol!=="https:"||j.protocol!=="https:"||i.username||i.password||j.username||j.password)throw new Error("OIDC issuer and JWKS URL must use HTTPS without embedded credentials.");
const cacheMs=Number(env.AIFIAR_OIDC_JWKS_CACHE_MS??300000);if(!Number.isInteger(cacheMs)||cacheMs<10000||cacheMs>3600000)throw new Error("OIDC JWKS cache must be 10 seconds to one hour.");
return{issuer:i.href,audience,jwksUrl:j,cacheMs};

export interface OidcConfig {
issuer: string;
audience: string;
jwksUrl: URL;
cacheMs: number;
}

interface Jwk {
kid?: string;
kty?: string;
use?: string;
alg?: string;
key_ops?: string[];
n?: string;
e?: string;
}

const TOOLS = ["aifiar_status", "aifiar_list_models", "aifiar_get_instructions", "aifiar_prepare_repository"];
const PROFILES = ["claude", "gpt", "grok", "codex", "cursor"];
const isRecord = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === "object" && !Array.isArray(value);

export function loadOidcConfig(env = process.env): OidcConfig | null {
const issuer = env.AIFIAR_OIDC_ISSUER;
const audience = env.AIFIAR_OIDC_AUDIENCE;
const jwks = env.AIFIAR_OIDC_JWKS_URL;
if (!issuer && !audience && !jwks) return null;
if (!issuer || !audience || !jwks) {
throw new Error("OIDC requires issuer, audience, and JWKS URL together.");
}

let issuerUrl: URL;
let jwksUrl: URL;
try {
issuerUrl = new URL(issuer);
jwksUrl = new URL(jwks);
} catch {
throw new Error("OIDC issuer and JWKS URL must be absolute URLs.");
}

if (
issuerUrl.protocol !== "https:" ||
jwksUrl.protocol !== "https:" ||
issuerUrl.username ||
issuerUrl.password ||
jwksUrl.username ||
jwksUrl.password ||
issuerUrl.search ||
issuerUrl.hash ||
jwksUrl.hash
) {
throw new Error("OIDC issuer and JWKS URL must use HTTPS without credentials or fragments.");
}
if (!audience.trim() || audience.length > 512) {
throw new Error("OIDC audience must be a non-empty value of at most 512 characters.");
}

const cacheMs = Number(env.AIFIAR_OIDC_JWKS_CACHE_MS ?? 300000);
if (!Number.isInteger(cacheMs) || cacheMs < 10000 || cacheMs > 3600000) {
throw new Error("OIDC JWKS cache must be 10 seconds to one hour.");
}

return { issuer: issuerUrl.href, audience, jwksUrl, cacheMs };
}

export function createOidcVerifier(
config: OidcConfig,
fetcher: typeof fetch = fetch,
now: () => number = Date.now
) {
let cached: { expires: number; keys: Jwk[] } | undefined;
let pending: Promise<Jwk[]> | undefined;

async function fetchKeys(): Promise<Jwk[]> {
const response = await fetcher(config.jwksUrl, {
method: "GET",
headers: { accept: "application/json" },
redirect: "error",
signal: AbortSignal.timeout(5000)
});
if (!response.ok) throw new Error("JWKS fetch failed.");
const body = await response.text();
if (body.length > 1048576) throw new Error("JWKS response too large.");

let parsed: unknown;
try {
parsed = JSON.parse(body);
} catch {
throw new Error("Invalid JWKS JSON.");
}
if (!isRecord(parsed) || !Array.isArray(parsed.keys) || parsed.keys.length < 1 || parsed.keys.length > 100) {
throw new Error("JWKS must contain 1 to 100 keys.");
}

const keys = parsed.keys.filter((key): key is Jwk =>
isRecord(key) &&
key.kty === "RSA" &&
(key.use === undefined || key.use === "sig") &&
(key.alg === undefined || key.alg === "RS256") &&
(key.key_ops === undefined || (Array.isArray(key.key_ops) && key.key_ops.includes("verify"))) &&
typeof key.kid === "string" &&
key.kid.length > 0 &&
key.kid.length <= 256 &&
typeof key.n === "string" &&
typeof key.e === "string"
);

if (!keys.length) throw new Error("No supported RSA signing keys.");
const ids = keys.map(key => key.kid);
if (new Set(ids).size !== ids.length) throw new Error("JWKS contains duplicate signing key IDs.");
return keys;
}

async function getKeys(forceRefresh = false): Promise<Jwk[]> {
if (!forceRefresh && cached && cached.expires > now()) return cached.keys;
if (!pending) {
pending = fetchKeys()
.then(keys => {
cached = { keys, expires: now() + config.cacheMs };
return keys;
})
.finally(() => {
pending = undefined;
});
}
return pending;
}

return async (authorization: string | undefined): Promise<RemotePrincipal | null> => {
if (!authorization || !/^Bearer [A-Za-z0-9._~+/-]+=*$/i.test(authorization)) return null;
const token = authorization.slice(7);
if (token.length > 16384) return null;

const parts = token.split(".");
if (parts.length !== 3 || parts.some(part => !part)) return null;

let header: unknown;
let claims: unknown;
try {
header = JSON.parse(Buffer.from(parts[0]!, "base64url").toString("utf8"));
claims = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8"));
} catch {
return null;
}

if (!isRecord(header) || header.alg !== "RS256" || typeof header.kid !== "string" || !header.kid) return null;
if (header.crit !== undefined || header.zip !== undefined || header.jku !== undefined || header.x5u !== undefined) return null;
if (!isRecord(claims)) return null;

const audiences = typeof claims.aud === "string"
? [claims.aud]
: Array.isArray(claims.aud) && claims.aud.every(value => typeof value === "string")
? claims.aud as string[]
: [];
const nowSeconds = Math.floor(now() / 1000);

if (
claims.iss !== config.issuer ||
!audiences.includes(config.audience) ||
typeof claims.exp !== "number" ||
!Number.isSafeInteger(claims.exp) ||
claims.exp <= nowSeconds ||
claims.exp > nowSeconds + 86400 ||
(claims.nbf !== undefined && (
typeof claims.nbf !== "number" ||
!Number.isSafeInteger(claims.nbf) ||
claims.nbf > nowSeconds + 30
)) ||
typeof claims.sub !== "string" ||
!/^[A-Za-z0-9._:@-]{1,128}$/.test(claims.sub)
) return null;

const scopes = typeof claims.scope === "string"
? claims.scope.split(/\s+/).filter(Boolean)
: Array.isArray(claims.scp) && claims.scp.every(value => typeof value === "string")
? claims.scp as string[]
: [];

if (
!scopes.includes("aifiar:read") ||
typeof claims.aifiar_profile !== "string" ||
!PROFILES.includes(claims.aifiar_profile) ||
!Array.isArray(claims.aifiar_tools) ||
claims.aifiar_tools.length === 0 ||
!claims.aifiar_tools.every((tool: unknown) => typeof tool === "string" && TOOLS.includes(tool)) ||
new Set(claims.aifiar_tools).size !== claims.aifiar_tools.length
) return null;

const requestsPerMinute = claims.aifiar_requests_per_minute ?? 60;
if (!Number.isInteger(requestsPerMinute) || Number(requestsPerMinute) < 1 || Number(requestsPerMinute) > 600) {
return null;
}

try {
let keys = await getKeys();
let jwk = keys.find(key => key.kid === header.kid);
if (!jwk) {
keys = await getKeys(true);
jwk = keys.find(key => key.kid === header.kid);
}
if (!jwk) return null;

const key = createPublicKey({ key: jwk as JsonWebKey, format: "jwk" });
if (key.asymmetricKeyType !== "rsa" || (key.asymmetricKeyDetails?.modulusLength ?? 0) < 2048) return null;

const signingInput = Buffer.from(parts[0] + "." + parts[1], "ascii");
const signature = Buffer.from(parts[2]!, "base64url");
if (!verifySignature("RSA-SHA256", signingInput, key, signature)) return null;

return {
subject: claims.sub,
profile: claims.aifiar_profile as RemotePrincipal["profile"],
tools: claims.aifiar_tools as string[],
requestsPerMinute: Number(requestsPerMinute)
};
} catch {
return null;
}
};
}
export function createOidcVerifier(config:OidcConfig,fetcher:typeof fetch=fetch,now:()=>number=Date.now){
let cached:{expires:number;keys:Jwk[]}|undefined;let pending:Promise<Jwk[]>|undefined;
async function getKeys():Promise<Jwk[]>{
if(cached&&cached.expires>now())return cached.keys;
if(!pending)pending=(async()=>{const response=await fetcher(config.jwksUrl,{method:"GET",headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(5000)});if(!response.ok)throw new Error("JWKS fetch failed.");const body=await response.text();if(body.length>1048576)throw new Error("JWKS response too large.");let parsed:unknown;try{parsed=JSON.parse(body)}catch{throw new Error("Invalid JWKS JSON.");}if(!isRecord(parsed)||!Array.isArray(parsed.keys)||parsed.keys.length<1||parsed.keys.length>100)throw new Error("JWKS must contain 1 to 100 keys.");const keys=parsed.keys.filter((k):k is Jwk=>isRecord(k)&&k.kty==="RSA"&&k.use!=="enc"&&k.alg!=="HS256"&&typeof k.kid==="string"&&typeof k.n==="string"&&typeof k.e==="string");if(!keys.length)throw new Error("No supported RSA signing keys.");cached={keys,expires:now()+config.cacheMs};return keys})().finally(()=>{pending=undefined});
return pending;
}
return async(header:string|undefined):Promise<RemotePrincipal|null>=>{
if(!header||!/^Bearer [A-Za-z0-9._~+/-]+=*$/i.test(header))return null;const token=header.slice(7);if(token.length>16384)return null;const parts=token.split(".");if(parts.length!==3)return null;
let h:unknown,c:unknown;try{h=JSON.parse(Buffer.from(parts[0]!,"base64url").toString());c=JSON.parse(Buffer.from(parts[1]!,"base64url").toString())}catch{return null}
if(!isRecord(h)||h.alg!=="RS256"||typeof h.kid!=="string"||!isRecord(c))return null;
const aud=typeof c.aud==="string"?[c.aud]:Array.isArray(c.aud)?c.aud:[],nowSec=Math.floor(now()/1000);
if(c.iss!==config.issuer||!aud.includes(config.audience)||typeof c.exp!=="number"||!Number.isFinite(c.exp)||c.exp<=nowSec||c.exp>nowSec+86400||(typeof c.nbf==="number"&&c.nbf>nowSec+30)||typeof c.sub!=="string"||!/^[A-Za-z0-9._:@-]{1,128}$/.test(c.sub))return null;
const scopes=typeof c.scope==="string"?c.scope.split(/\s+/):Array.isArray(c.scp)?c.scp:[];
if(!scopes.includes("aifiar:read")||typeof c.aifiar_profile!=="string"||!PROFILES.includes(c.aifiar_profile)||!Array.isArray(c.aifiar_tools)||c.aifiar_tools.length===0||!c.aifiar_tools.every((x:unknown)=>typeof x==="string"&&TOOLS.includes(x))||new Set(c.aifiar_tools).size!==c.aifiar_tools.length)return null;
const rpm=c.aifiar_requests_per_minute??60;if(!Number.isInteger(rpm)||Number(rpm)<1||Number(rpm)>600)return null;
try{const jwks=await getKeys(),jwk=jwks.find(k=>k.kid===h.kid);if(!jwk)return null;const key=createPublicKey({key:jwk as JsonWebKey,format:"jwk"});if(!verifySignature("RSA-SHA256",Buffer.from(parts[0]+"."+parts[1]),key,Buffer.from(parts[2]!,"base64url")))return null;return{subject:c.sub,profile:c.aifiar_profile as RemotePrincipal["profile"],tools:c.aifiar_tools as string[],requestsPerMinute:Number(rpm)}}catch{return null}
};
}
Loading
Loading