local ext = require('panto').ext local json = ext.json local async = require('panto_mcp.async') local config = require('panto_mcp.config') local M = {}; M.__index=M local function nonempty(v) return type(v)=='string' and v~='' and not v:find('[%z\1-\32\127]') end -- Credentials, fragments and ambiguous authorities are never accepted. function M.url(value) if type(value)~='string' or value:find('[%z\1-\32\127\\#]') then return nil end local scheme,authority,tail=value:match('^([A-Za-z]+)://([^/?]+)(.*)$') if not scheme then return nil end scheme=scheme:lower(); if scheme~='https' and scheme~='http' then return nil end local host,port if authority:sub(1,1)=='[' then host,port=authority:match('^(%[[%x:]+%])(:?%d*)$') else host,port=authority:match('^([A-Za-z0-9.-]+)(:?%d*)$') end if not host or port==':' then return nil end if port~='' and (not tonumber(port:sub(2)) or tonumber(port:sub(2))<1 or tonumber(port:sub(2))>65535) then return nil end host=host:lower() local literal_loopback=host=='[::1]' local mapped_loopback=false if host:sub(1,1)=='[' then local address=host:sub(2,-2); local left,right=address:match('^(.-)::(.-)$') local groups={} for group in (left or address):gmatch('[^:]+') do groups[#groups+1]=tonumber(group,16) end if left then local suffix={}; for group in right:gmatch('[^:]+') do suffix[#suffix+1]=tonumber(group,16) end while #groups+#suffix<8 do groups[#groups+1]=0 end for _,group in ipairs(suffix) do groups[#groups+1]=group end end if #groups==8 then local zeros=true; for i=1,5 do if groups[i]~=0 then zeros=false end end literal_loopback=zeros and groups[6]==0 and groups[7]==0 and groups[8]==1 mapped_loopback=zeros and groups[6]==0xffff and groups[7]>=0x7f00 and groups[7]<=0x7fff end end local a,b,c,d=host:match('^(%d+)%.(%d+)%.(%d+)%.(%d+)$') if a then for _,octet in ipairs({a,b,c,d}) do if (#octet>1 and octet:sub(1,1)=='0') or tonumber(octet)>255 then return nil end end literal_loopback=a=='127' elseif host:match('^[%d.]+$') then return nil end for octet in host:gmatch('[^.]+') do if octet:match('^0x%x+$') then return nil end end if scheme=='http' and not literal_loopback then return nil end if (scheme=='https' and port==':443') or (scheme=='http' and port==':80') then port='' end local origin=scheme..'://'..host..port if tail=='/' then tail='' end return origin..tail,origin,tail:match('^[^?]*'),literal_loopback or mapped_loopback or host=='localhost' or host=='localhost.' or host:match('%.localhost%.?$')~=nil end function M.prm_urls(resource) local _,origin,path=M.url(resource); if not origin then return {} end local root=origin..'/.well-known/oauth-protected-resource' return path~='' and {root..path,root} or {root} end function M.metadata_urls(issuer) local _,origin,path=M.url(issuer) if not origin or issuer:find('?',1,true) then return {} end path=path:gsub('/$','') local urls={origin..'/.well-known/oauth-authorization-server'..path,origin..'/.well-known/openid-configuration'..path} if path~='' then urls[#urls+1]=origin..path..'/.well-known/openid-configuration' end return urls end function M.scopes(value) local out,seen={},{} if type(value)=='string' then local parts={}; for part in value:gmatch('%S+') do parts[#parts+1]=part end; value=parts end if type(value)~='table' then return out end for _,v in ipairs(value) do local valid=type(v)=='string' and v~='' if valid then for i=1,#v do local byte=v:byte(i) if byte<33 or byte>126 or byte==34 or byte==92 then valid=false; break end end end if valid and not seen[v] then seen[v]=true; out[#out+1]=v end end return out end function M.union(a,b) local out=M.scopes(a); local seen={}; for _,v in ipairs(out) do seen[v]=true end for _,v in ipairs(M.scopes(b)) do if not seen[v] then seen[v]=true; out[#out+1]=v end end return out end -- Commas inside quoted strings are not challenge separators; quoted-pairs are unescaped. function M.challenge(header) if type(header)~='string' or #header>16384 or header:find('[\r\n%z]') then return {} end local chunks,begin,quoted,escaped={},1,false,false for i=1,#header do local c=header:sub(i,i) if escaped then escaped=false elseif quoted and c=='\\' then escaped=true elseif c=='"' then quoted=not quoted elseif c==',' and not quoted then chunks[#chunks+1]=header:sub(begin,i-1); begin=i+1 end end if quoted or escaped then return {} end chunks[#chunks+1]=header:sub(begin) local candidates,current={},nil for _,chunk in ipairs(chunks) do chunk=chunk:match('^%s*(.-)%s*$') local scheme,rest=chunk:match('^([%w!#$%%&\'*+.^_`|~-]+)%s+(.+)$') if scheme and not rest:match('^=') then current={scheme=scheme:lower()}; candidates[#candidates+1]=current; chunk=rest elseif chunk:match('^[%w_-]+$') then current={scheme=chunk:lower()}; candidates[#candidates+1]=current; chunk='' end if current and chunk~='' then local key,value=chunk:match('^([%w!#$%%&\'*+.^_`|~-]+)%s*=%s*(.-)%s*$') if key then key=key:lower() if value:sub(1,1)=='"' and value:sub(-1)=='"' then value=value:sub(2,-2):gsub('\\(.)','%1') elseif not value:match('^[%w!#$%%&\'*+.^_`|~-]+$') then current.invalid=true end if current[key]~=nil then current.invalid=true end current[key]=value else current.invalid=true end end end local first for _,c in ipairs(candidates) do if c.scheme=='bearer' and not c.invalid then local safe={resource_metadata=c.resource_metadata,scope=c.scope,error=c.error} if c.resource_metadata then return safe end first=first or safe end end return first or {} end function M.validate_metadata(metadata,issuer) if type(metadata)~='table' or metadata.issuer~=issuer then return nil,'OAuth metadata issuer mismatch' end if not M.url(metadata.authorization_endpoint) or not M.url(metadata.token_endpoint) then return nil,'OAuth metadata has unsafe endpoints' end local s256=false for _,method in ipairs(type(metadata.code_challenge_methods_supported)=='table' and metadata.code_challenge_methods_supported or {}) do if method=='S256' then s256=true end end if not s256 then return nil,'OAuth server must advertise PKCE S256' end if metadata.authorization_response_iss_parameter_supported~=nil and type(metadata.authorization_response_iss_parameter_supported)~='boolean' then return nil,'Invalid OAuth issuer-response metadata' end return true end function M.session_name(server,resource,issuer,client_id) local identity=json.encode({resource=resource,issuer=issuer,client_id=client_id}) return 'mcp.'..server:sub(1,91)..'.'..require('panto_mcp.hash').sha256(identity):sub(1,32) end function M.new(cfg,opts) opts=opts or {} local resource,origin,_,loopback=M.url(cfg.url) local self=setmetatable({cfg=cfg,name=cfg.auth,auth=opts.auth or ext.auth, state=opts.state or ext.state,request_fn=opts.request_fn or ext.http_request, timer_factory=opts.timer_factory or async.timer,clock=opts.clock or require('luv').now, timers={},resource=resource,origin=origin,loopback=loopback},M) self.key='mcp.oauth.server_'..cfg.name if not cfg.auth and self.state then local stored=self.state.get(self.key) if type(stored)=='table' and stored.version==2 and stored.fingerprint==cfg.fingerprint and stored.resource==resource and self:available() then self.name=stored.name self:define(stored) end end return self end function M:available() return type(self.auth)=='table' and type(self.auth.define)=='function' and type(self.auth.status)=='function' and type(self.auth.login)=='function' and type(self.auth.refresh)=='function' and type(self.auth.complete)=='function' end function M:login_error() return 'Authentication required; run /mcp-login '..self.cfg.name end function M:recovery_error(text) if self.cfg.auth then return text..'; check configured auth with panto auth login/status' end local hint=(self.cfg.oauth and self.cfg.oauth.client_id) and 'check the configured OAuth client/issuer' or ('try /mcp-login '..self.cfg.name..' --reregister to replace a stale DCR client') return text..'; '..hint end function M:usable() local state=self:auth_status().state return state=='logged_in' or (state=='pending' and self.login_usable==true) end function M:configured_error() return 'Configured auth session rejected (HTTP 401); check its credentials/type with panto auth login/status' end function M:auth_status() if not self.name or not self:available() then return {state='logged_out'} end local now=self.clock() if not self.cached_status or now>=(self.status_at or 0)+1000 then self.cached_status=self.auth.status(self.name) or {state='logged_out'}; self.status_at=now end return self.cached_status end function M:status() if not self:available() then return 'unavailable' end if not self.cfg.auth and not self.definition then return 'undiscovered' end local state=self:auth_status().state if self.login_required and state~='pending' then return 'login_required' end return state end function M:request_auth() if self.cfg.auth then return self.cfg.auth end if self.definition and (self.refreshing or (not self.login_required and self:usable())) then return self.name end end function M:blocked() if self.refreshing then return false end return not self.cfg.auth and self.definition and (self.login_required or not self:usable()) end function M:before_request() if self.refreshing then local ok,err=self.refreshing:await(); if not ok then return nil,err end end if self:blocked() then return nil,self:login_error() end if not self.definition and self.discovery_error and self.clock()=300 then future:resolve(nil,'OAuth discovery/registration request failed'); return end local decoded,value=pcall(json.decode,response.body or '') if not decoded or type(value)~='table' then future:resolve(nil,'Invalid OAuth metadata JSON'); return end future:resolve(value) end) if not ok or not handle then return nil,'OAuth HTTP request could not start' end self.requests=self.requests or {}; self.requests[handle]=future local value,err=future:await(); self.requests[handle]=nil return value,err end function M:discover(challenge) if self.cfg.auth then return nil,self:configured_error() end challenge=challenge or {} if self.definition then return true end if self.discovering then return self.discovering:await() end if self.discovery_error and self.clock()