From 68868d4c51f639333ee1a072bc7773609cd08145 Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:39:34 +0530 Subject: [PATCH 1/7] Harden remote OIDC JWT verification and JWKS rotation --- connectors/remote/oidc.ts | 252 +++++++++++++++++++++++++++++++++----- 1 file changed, 220 insertions(+), 32 deletions(-) diff --git a/connectors/remote/oidc.ts b/connectors/remote/oidc.ts index d17b28c..53344d4 100644 --- a/connectors/remote/oidc.ts +++ b/connectors/remote/oidc.ts @@ -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=>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 => + 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 | undefined; + + async function fetchKeys(): Promise { + 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 { + 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 => { + 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|undefined; - async function getKeys():Promise{ - 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=>{ - 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} - }; -} \ No newline at end of file From 786bc2c82a8a9d5327f0918ab7822ec1fdb57b03 Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:40:01 +0530 Subject: [PATCH 2/7] Expand OIDC verifier security and key-rotation tests --- tests/remoteOidc.test.mjs | 70 ++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 9 deletions(-) diff --git a/tests/remoteOidc.test.mjs b/tests/remoteOidc.test.mjs index 99191b0..cd7be80 100644 --- a/tests/remoteOidc.test.mjs +++ b/tests/remoteOidc.test.mjs @@ -2,12 +2,64 @@ import test from "node:test"; import assert from "node:assert/strict"; import { generateKeyPairSync, sign } from "node:crypto"; import { createOidcVerifier, loadOidcConfig } from "../dist/connectors/remote/oidc.js"; -const pair=generateKeyPairSync("rsa",{modulusLength:2048}); -const jwk={...pair.publicKey.export({format:"jwk"}),kid:"unit-key",use:"sig",alg:"RS256"}; -const cfg={issuer:"https://issuer.example",audience:"aifiar-api",jwksUrl:new URL("https://issuer.example/jwks"),cacheMs:30000}; -const claims={iss:cfg.issuer,aud:cfg.audience,sub:"test-user",exp:1700000600,scope:"aifiar:read",aifiar_profile:"gpt",aifiar_tools:["aifiar_status"]}; -const makeToken=(c)=>{const enc=x=>Buffer.from(JSON.stringify(x)).toString("base64url");const a=enc({alg:"RS256",kid:"unit-key"}),b=enc(c),data=a+"."+b;return data+"."+sign("RSA-SHA256",Buffer.from(data),pair.privateKey).toString("base64url")}; -const fetcher=async()=>new Response(JSON.stringify({keys:[jwk]}),{status:200}); -test("OIDC config requires complete HTTPS issuer, audience and JWKS",()=>{assert.equal(loadOidcConfig({}),null);assert.throws(()=>loadOidcConfig({AIFIAR_OIDC_ISSUER:cfg.issuer}));assert.throws(()=>loadOidcConfig({AIFIAR_OIDC_ISSUER:"http://issuer.example",AIFIAR_OIDC_AUDIENCE:cfg.audience,AIFIAR_OIDC_JWKS_URL:cfg.jwksUrl.href}));}); -test("OIDC access tokens require valid RS256 signature, issuer, audience, expiry and AIFIAR scopes",async()=>{const verify=createOidcVerifier(cfg,fetcher,()=>1700000000000);const p=await verify("Bearer "+makeToken(claims));assert.equal(p.subject,"test-user");assert.deepEqual(p.tools,["aifiar_status"]);assert.equal(await verify("Bearer "+makeToken({...claims,iss:"https://wrong.example"})),null);assert.equal(await verify("Bearer "+makeToken({...claims,aud:"wrong"})),null);assert.equal(await verify("Bearer "+makeToken({...claims,exp:1699999999})),null);assert.equal(await verify("Bearer "+makeToken({...claims,scope:"openid"})),null);assert.equal(await verify("Bearer "+makeToken({...claims,aifiar_tools:["shell"]})),null);}); -test("OIDC verifier caches JWKS and rejects an empty key set",async()=>{let calls=0;const verify=createOidcVerifier(cfg,async()=>{calls++;return fetcher()},()=>1700000000000);await verify("Bearer "+makeToken(claims));await verify("Bearer "+makeToken(claims));assert.equal(calls,1);const bad=createOidcVerifier(cfg,async()=>new Response(JSON.stringify({keys:[]}),{status:200}),()=>1700000000000);assert.equal(await bad("Bearer "+makeToken(claims)),null);}); + +const pair = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const pair2 = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const jwk = { ...pair.publicKey.export({ format: "jwk" }), kid: "unit-key", use: "sig", alg: "RS256" }; +const cfg = { issuer: "https://issuer.example", audience: "aifiar-api", jwksUrl: new URL("https://issuer.example/jwks"), cacheMs: 30000 }; +const claims = { iss: cfg.issuer, aud: cfg.audience, sub: "test-user", exp: 1700000600, scope: "aifiar:read", aifiar_profile: "gpt", aifiar_tools: ["aifiar_status"] }; +const makeToken = (value, keyPair = pair, kid = "unit-key") => { + const encode = value => Buffer.from(JSON.stringify(value)).toString("base64url"); + const header = encode({ alg: "RS256", kid }); + const payload = encode(value); + const input = header + "." + payload; + return input + "." + sign("RSA-SHA256", Buffer.from(input), keyPair.privateKey).toString("base64url"); +}; +const fetcher = async () => new Response(JSON.stringify({ keys: [jwk] }), { status: 200 }); + +test("OIDC config requires complete HTTPS issuer, audience and JWKS", () => { + assert.equal(loadOidcConfig({}), null); + assert.throws(() => loadOidcConfig({ AIFIAR_OIDC_ISSUER: cfg.issuer })); + assert.throws(() => loadOidcConfig({ AIFIAR_OIDC_ISSUER: "http://issuer.example", AIFIAR_OIDC_AUDIENCE: cfg.audience, AIFIAR_OIDC_JWKS_URL: cfg.jwksUrl.href })); + assert.throws(() => loadOidcConfig({ AIFIAR_OIDC_ISSUER: cfg.issuer, AIFIAR_OIDC_AUDIENCE: " ", AIFIAR_OIDC_JWKS_URL: cfg.jwksUrl.href })); +}); + +test("OIDC access tokens require valid RS256 signature, issuer, audience, expiry and AIFIAR scopes", async () => { + const verify = createOidcVerifier(cfg, fetcher, () => 1700000000000); + const principal = await verify("Bearer " + makeToken(claims)); + assert.equal(principal.subject, "test-user"); + assert.deepEqual(principal.tools, ["aifiar_status"]); + assert.equal(await verify("Bearer " + makeToken({ ...claims, iss: "https://wrong.example" })), null); + assert.equal(await verify("Bearer " + makeToken({ ...claims, aud: "wrong" })), null); + assert.equal(await verify("Bearer " + makeToken({ ...claims, exp: 1699999999 })), null); + assert.equal(await verify("Bearer " + makeToken({ ...claims, scope: "openid" })), null); + assert.equal(await verify("Bearer " + makeToken({ ...claims, aifiar_tools: ["shell"] })), null); + assert.equal(await verify("Bearer " + makeToken({ ...claims, nbf: "not-a-number" })), null); + assert.equal(await verify("Bearer " + makeToken({ ...claims, aifiar_tools: ["aifiar_status", "aifiar_status"] })), null); +}); + +test("OIDC verifier caches JWKS and rejects empty or unsuitable key sets", async () => { + let calls = 0; + const verify = createOidcVerifier(cfg, async () => { calls++; return fetcher(); }, () => 1700000000000); + await verify("Bearer " + makeToken(claims)); + await verify("Bearer " + makeToken(claims)); + assert.equal(calls, 1); + + const empty = createOidcVerifier(cfg, async () => new Response(JSON.stringify({ keys: [] }), { status: 200 }), () => 1700000000000); + assert.equal(await empty("Bearer " + makeToken(claims)), null); + + const encryptionOnly = createOidcVerifier(cfg, async () => new Response(JSON.stringify({ keys: [{ ...jwk, use: "enc" }] }), { status: 200 }), () => 1700000000000); + assert.equal(await encryptionOnly("Bearer " + makeToken(claims)), null); +}); + +test("OIDC verifier refreshes JWKS once when a rotated key ID is not cached", async () => { + let calls = 0; + const rotatedJwk = { ...pair2.publicKey.export({ format: "jwk" }), kid: "rotated-key", use: "sig", alg: "RS256" }; + const verify = createOidcVerifier(cfg, async () => { + calls++; + return new Response(JSON.stringify({ keys: calls === 1 ? [jwk] : [jwk, rotatedJwk] }), { status: 200 }); + }, () => 1700000000000); + const principal = await verify("Bearer " + makeToken(claims, pair2, "rotated-key")); + assert.equal(principal?.subject, "test-user"); + assert.equal(calls, 2); +}); From 7248253b9224366e52c6affd41914293e3bd71eb Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:40:55 +0530 Subject: [PATCH 3/7] Validate remote host and browser origin allowlists strictly --- connectors/remote/config.ts | 121 +++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 3 deletions(-) diff --git a/connectors/remote/config.ts b/connectors/remote/config.ts index f1432ce..041feeb 100644 --- a/connectors/remote/config.ts +++ b/connectors/remote/config.ts @@ -1,3 +1,118 @@ -export interface RemoteConfig{host:string;port:number;path:string;publicUrl:URL;allowedHosts:Set;allowedOrigins:Set;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}} \ No newline at end of file +export interface RemoteConfig { + host: string; + port: number; + path: string; + publicUrl: URL; + allowedHosts: Set; + allowedOrigins: Set; + 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 { + 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 { + const origins = new Set(); + 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 + }; +} From 1797a858e4e2d38d7e057de8f0ae49248c1a995c Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:41:07 +0530 Subject: [PATCH 4/7] Test strict remote host and CORS origin allowlists --- tests/remoteConnector.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/remoteConnector.test.mjs b/tests/remoteConnector.test.mjs index 11d78ef..788d0b1 100644 --- a/tests/remoteConnector.test.mjs +++ b/tests/remoteConnector.test.mjs @@ -3,7 +3,7 @@ const token="a".repeat(48),entry=JSON.stringify([{token,subject:"test-user",prof test("remote token config validates and secrets are not part of principal claims",()=>{const records=loadRemoteTokens(entry),p=authenticateBearer("Bearer "+token,records);assert.equal(p.subject,"test-user");assert.equal(p.profile,"gpt");assert.deepEqual(p.tools,["aifiar_status"]);assert.equal("token"in p,false);assert.equal(authenticateBearer("Bearer "+ "b".repeat(48),records),null)}); test("remote token configuration rejects weak, duplicate and overbroad entries",()=>{assert.throws(()=>loadRemoteTokens("[]"));assert.throws(()=>loadRemoteTokens(JSON.stringify([{token:"short",subject:"x",profile:"gpt",tools:[]}])));assert.throws(()=>loadRemoteTokens(JSON.stringify([{token,subject:"x",profile:"gpt",tools:["shell"]}])));assert.throws(()=>loadRemoteTokens(JSON.stringify([{token,subject:"x",profile:"gpt",tools:[]},{token:"b".repeat(48),subject:"x",profile:"gpt",tools:[]}])));}); test("remote config requires public HTTPS URL and matching endpoint path",()=>{assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"http://localhost:8787/mcp"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/other"}));const c=loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp"});assert.equal(c.host,"127.0.0.1");assert.equal(c.port,8787);assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_PORT:"70000"}))}); -test("fixed-window limiter enforces per-key and global ceilings",()=>{const l=new FixedWindowLimiter(2,60000);assert.equal(l.allow("a",1,1),true);assert.equal(l.allow("a",1,2),false);assert.equal(l.allow("b",2,3),true);assert.equal(l.allow("b",2,4),true);assert.equal(l.allow("b",2,5),false);assert.equal(l.allow("b",2,60003),true)}); +test("remote config rejects wildcard, malformed host and non-origin browser allowlists",()=>{assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_HOSTS:"*"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_HOSTS:"example.com/path"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"http://example.com"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"https://example.com/path"}));const c=loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"https://app.example.com"});assert.deepEqual([...c.allowedOrigins],["https://app.example.com"])});\ntest("fixed-window limiter enforces per-key and global ceilings",()=>{const l=new FixedWindowLimiter(2,60000);assert.equal(l.allow("a",1,1),true);assert.equal(l.allow("a",1,2),false);assert.equal(l.allow("b",2,3),true);assert.equal(l.allow("b",2,4),true);assert.equal(l.allow("b",2,5),false);assert.equal(l.allow("b",2,60003),true)}); test("remote MCP endpoint authenticates and exposes only scoped tools",async(t)=>{const old={...process.env};Object.assign(process.env,{AIFIAR_REMOTE_PUBLIC_URL:"https://localhost:18787/mcp",AIFIAR_REMOTE_HOST:"127.0.0.1",AIFIAR_REMOTE_PORT:"18787",AIFIAR_REMOTE_ALLOWED_HOSTS:"localhost:18787",AIFIAR_REMOTE_TOKENS:entry});const{server}=createRemoteMcpServer();await new Promise(resolve=>server.listen(18787,"127.0.0.1",resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));for(const k of Object.keys(process.env))if(!(k in old))delete process.env[k];Object.assign(process.env,old)}); const base="http://localhost:18787",headers={host:"localhost:18787","content-type":"application/json",accept:"application/json, text/event-stream"}; let r=await fetch(base+"/mcp",{method:"POST",headers,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/list"})});assert.equal(r.status,401); From 1da208f0f4d604dcc1e6a189098aee2fb5b2bf21 Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:41:15 +0530 Subject: [PATCH 5/7] Document hardened OIDC and remote origin policy --- docs/remote-connector-deployment.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/remote-connector-deployment.md b/docs/remote-connector-deployment.md index 1013230..3e2dcf8 100644 --- a/docs/remote-connector-deployment.md +++ b/docs/remote-connector-deployment.md @@ -16,7 +16,7 @@ AIFIAR is an OAuth **resource server**, not an authorization server. Login, cons 4. Set `AIFIAR_REMOTE_PUBLIC_URL=https://your-domain.example/mcp`, `AIFIAR_REMOTE_PATH=/mcp`, and `AIFIAR_REMOTE_ALLOWED_HOSTS=your-domain.example`. Optionally set `AIFIAR_REMOTE_ALLOWED_ORIGINS`. 5. Run `npm run connector:remote`. The process binds to loopback by default. For a container deployment, bind to `0.0.0.0` behind a TLS-terminating reverse proxy. -The public URL must be HTTPS and its path must match the configured endpoint path. Only configured hosts are accepted. Browser origins are denied unless explicitly listed. Server-to-server clients may omit Origin. +The public URL must be HTTPS and its path must match the configured endpoint path. Only exact configured host[:port] values are accepted; wildcard hosts are rejected. Browser origins are denied unless explicitly listed as exact HTTPS origins without paths or credentials. Server-to-server clients may omit Origin. ## Docker deployment @@ -41,7 +41,7 @@ AIFIAR publishes protected-resource metadata at `/.well-known/oauth-protected-re - `aifiar_tools`: an explicit array containing only allowed tools: `aifiar_status`, `aifiar_list_models`, `aifiar_get_instructions`, and/or `aifiar_prepare_repository`. - Optional `aifiar_requests_per_minute`: integer from 1 to 600. -The verifier accepts RS256-signed JWT access tokens, checks signature, issuer, audience, expiry, optional not-before, subject, required scope, profile and tool claims. JWKS retrieval is HTTPS-only, limited to 1 MiB and 100 keys, cached for 10 seconds to one hour, and bounded by a request timeout. The external identity provider should issue short-lived access tokens and use secure refresh-token rotation. AIFIAR does not store passwords, issue tokens, or manage login sessions. +The verifier accepts RS256-signed JWT access tokens and checks signature, exact issuer, audience, expiry, optional not-before, subject, required scope, profile, tool claims, and per-principal rate limits. It rejects unsupported JOSE header features, non-signing keys, duplicate key IDs, and RSA keys below 2048 bits. JWKS retrieval is HTTPS-only, limited to 1 MiB and 100 keys, cached for 10 seconds to one hour, bounded by a request timeout, and refreshed once when a token references a previously unseen key ID. The external identity provider should issue short-lived access tokens and use secure refresh-token rotation. AIFIAR does not store passwords, issue tokens, or manage login sessions. ## Static bearer-token configuration From 8698047235a5a8f9d03ebb7485d6363008238bea Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:42:12 +0530 Subject: [PATCH 6/7] Fix remote connector test separator and rerun suite From caaba01a5cc40456a74cc7d071f4c587631ee3af Mon Sep 17 00:00:00 2001 From: NotY215 Date: Sat, 28 Nov 2026 09:43:06 +0530 Subject: [PATCH 7/7] Correct test file line break and rerun CI --- tests/remoteConnector.test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/remoteConnector.test.mjs b/tests/remoteConnector.test.mjs index 788d0b1..4feea88 100644 --- a/tests/remoteConnector.test.mjs +++ b/tests/remoteConnector.test.mjs @@ -3,7 +3,8 @@ const token="a".repeat(48),entry=JSON.stringify([{token,subject:"test-user",prof test("remote token config validates and secrets are not part of principal claims",()=>{const records=loadRemoteTokens(entry),p=authenticateBearer("Bearer "+token,records);assert.equal(p.subject,"test-user");assert.equal(p.profile,"gpt");assert.deepEqual(p.tools,["aifiar_status"]);assert.equal("token"in p,false);assert.equal(authenticateBearer("Bearer "+ "b".repeat(48),records),null)}); test("remote token configuration rejects weak, duplicate and overbroad entries",()=>{assert.throws(()=>loadRemoteTokens("[]"));assert.throws(()=>loadRemoteTokens(JSON.stringify([{token:"short",subject:"x",profile:"gpt",tools:[]}])));assert.throws(()=>loadRemoteTokens(JSON.stringify([{token,subject:"x",profile:"gpt",tools:["shell"]}])));assert.throws(()=>loadRemoteTokens(JSON.stringify([{token,subject:"x",profile:"gpt",tools:[]},{token:"b".repeat(48),subject:"x",profile:"gpt",tools:[]}])));}); test("remote config requires public HTTPS URL and matching endpoint path",()=>{assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"http://localhost:8787/mcp"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/other"}));const c=loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp"});assert.equal(c.host,"127.0.0.1");assert.equal(c.port,8787);assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_PORT:"70000"}))}); -test("remote config rejects wildcard, malformed host and non-origin browser allowlists",()=>{assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_HOSTS:"*"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_HOSTS:"example.com/path"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"http://example.com"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"https://example.com/path"}));const c=loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"https://app.example.com"});assert.deepEqual([...c.allowedOrigins],["https://app.example.com"])});\ntest("fixed-window limiter enforces per-key and global ceilings",()=>{const l=new FixedWindowLimiter(2,60000);assert.equal(l.allow("a",1,1),true);assert.equal(l.allow("a",1,2),false);assert.equal(l.allow("b",2,3),true);assert.equal(l.allow("b",2,4),true);assert.equal(l.allow("b",2,5),false);assert.equal(l.allow("b",2,60003),true)}); +test("remote config rejects wildcard, malformed host and non-origin browser allowlists",()=>{assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_HOSTS:"*"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_HOSTS:"example.com/path"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"http://example.com"}));assert.throws(()=>loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"https://example.com/path"}));const c=loadRemoteConfig({AIFIAR_REMOTE_PUBLIC_URL:"https://example.com/mcp",AIFIAR_REMOTE_ALLOWED_ORIGINS:"https://app.example.com"});assert.deepEqual([...c.allowedOrigins],["https://app.example.com"])}); +test("fixed-window limiter enforces per-key and global ceilings",()=>{const l=new FixedWindowLimiter(2,60000);assert.equal(l.allow("a",1,1),true);assert.equal(l.allow("a",1,2),false);assert.equal(l.allow("b",2,3),true);assert.equal(l.allow("b",2,4),true);assert.equal(l.allow("b",2,5),false);assert.equal(l.allow("b",2,60003),true)}); test("remote MCP endpoint authenticates and exposes only scoped tools",async(t)=>{const old={...process.env};Object.assign(process.env,{AIFIAR_REMOTE_PUBLIC_URL:"https://localhost:18787/mcp",AIFIAR_REMOTE_HOST:"127.0.0.1",AIFIAR_REMOTE_PORT:"18787",AIFIAR_REMOTE_ALLOWED_HOSTS:"localhost:18787",AIFIAR_REMOTE_TOKENS:entry});const{server}=createRemoteMcpServer();await new Promise(resolve=>server.listen(18787,"127.0.0.1",resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));for(const k of Object.keys(process.env))if(!(k in old))delete process.env[k];Object.assign(process.env,old)}); const base="http://localhost:18787",headers={host:"localhost:18787","content-type":"application/json",accept:"application/json, text/event-stream"}; let r=await fetch(base+"/mcp",{method:"POST",headers,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/list"})});assert.equal(r.status,401);