Documentation
¶
Overview ¶
Package oauth is the authorization server for Lectern's public MCP web connector (Streamable HTTP), ported from Grimoire's grimoire-mcp OAuth server — the same owner's MIT-licensed sibling project, already live in production for exactly this problem. See github.com/JeremiahM37/grimoire/go/internal/oauth for the original.
claude.ai adds an MCP server from its own cloud, not from the owner's browser: the thing that must authenticate a caller is a public HTTPS endpoint, and the only credential the connector UI can send is whatever a normal OAuth 2.1 authorization-code-with-PKCE flow hands it. It cannot be configured with a static bearer header, so LECTERN_AUTH_TOKEN does not reach this case at all — this package is what makes a connector-shaped client usable without one.
The design leans on a fact claude.ai's flow doesn't require of a typical public API: the approval step does not have to happen in its UI. Nothing in the OAuth authorization-code flow requires the authorization endpoint to be reachable from the same network as the client — only the browser doing the redirect has to reach it. So the /oauth/authorize page that actually grants access is never exposed on the public listener at all; it lives on a second, tailnet-only listener, and the owner's own browser is the only browser that ever loads it. See server.go for the split.
Tokens are opaque random values, stored hashed, matching the idiom the rest of the codebase already uses for secrets.
Index ¶
- Constants
- Variables
- func DefaultRedirectPatterns() []string
- func ValidScope(s string) bool
- func ValidateScopes(requested []string) []string
- func VerifyPKCE(verifier, challenge, method string) bool
- type AuthCode
- type AuthorizationServerMetadata
- type Client
- type ClientSummary
- type Config
- type Handler
- type Identity
- type Owner
- type ProtectedResourceMetadata
- type RedirectAllowlist
- type Store
- func (s *Store) CheckClientSecret(clientID, presented string) bool
- func (s *Store) Close() error
- func (s *Store) ConsumeAuthCode(code string) (*AuthCode, error)
- func (s *Store) CreateClient(name string, redirectURIs []string, authMethod string) (*Client, string, error)
- func (s *Store) GetClient(id string) (*Client, error)
- func (s *Store) IssueTokenPair(clientID string, scopes []string, resource string) (*TokenPair, error)
- func (s *Store) ListClients() ([]ClientSummary, error)
- func (s *Store) LookupAccessToken(raw string) (*TokenRecord, error)
- func (s *Store) RevokeClient(clientID string) error
- func (s *Store) RevokeToken(raw string) error
- func (s *Store) RotateRefresh(raw, clientID string) (*TokenPair, error)
- func (s *Store) SaveAuthCode(code string, ac AuthCode, ttl time.Duration) error
- type TokenPair
- type TokenRecord
Constants ¶
const ( ScopeRead = "lectern.read" ScopeWrite = "lectern.write" )
Scopes gate which MCP tools a token may call. There are exactly two: lectern.read covers every tool that only observes the board (sessions, tasks, projects, approvals, claims); lectern.write covers everything that starts a session, sends into one, files or dispatches work, or decides a build. decide_approval is not reachable through either scope — it is excluded from the web connector's tool list unconditionally, in internal/mcp/http.go, because an approval decision must come from the human, never from a remote LLM.
Variables ¶
var ( // ErrNotFound covers an unknown client, an unknown or already-consumed // code, and an unknown, expired or revoked token — deliberately one // error for all three, so none of these endpoints becomes an // enumeration oracle. ErrNotFound = errors.New("oauth: not found") // ErrExpired reports a code or token past its own deadline. Kept // distinct from ErrNotFound only where the caller needs a different // message; callers that don't care can treat both as "reject". ErrExpired = errors.New("oauth: expired") )
var AllScopes = []string{ScopeRead, ScopeWrite}
AllScopes is the full set, in the order presented on the consent page.
var DefaultScopes = []string{ScopeRead, ScopeWrite}
DefaultScopes are what a web connector is granted when the owner approves without touching the checkboxes. Both are on by default: unlike Grimoire's credential broker, neither Lectern scope can reach outside the board itself (no third-party spend, no arbitrary host file read — that path is refused separately for any remote caller, scoped or not, see internal/mcp/http.go), so there is no reason to make write an opt-in extra step.
var Now = time.Now
Now is overridden in tests that need to move expiry around without sleeping.
Functions ¶
func DefaultRedirectPatterns ¶
func DefaultRedirectPatterns() []string
DefaultRedirectPatterns are the hosts trusted out of the box: claude.ai and its subdomains, claude.com (Anthropic's newer domain, also seen in the custom-connector flow), chatgpt.com and openai.com subdomains, and localhost/127.0.0.1 on any port for the MCP Inspector and other local test clients. LECTERN_OAUTH_ALLOWED_REDIRECTS replaces this list; it does not merge with it, so an operator who wants Inspector testing alongside a custom set must re-list "http://localhost" themselves.
func ValidScope ¶
ValidScope reports whether s is one of the two scopes this server knows.
func ValidateScopes ¶
ValidateScopes filters requested down to the known scopes, deduplicated, order preserved. Unknown scope strings are dropped rather than rejected — a client asking for a scope this server never advertised is not an attack, and refusing outright would break a client that sends one extra scope this server doesn't have a tool for yet.
func VerifyPKCE ¶
VerifyPKCE checks a code_verifier against the code_challenge recorded at /oauth/authorize time.
Only S256 is accepted. OAuth 2.1 requires PKCE and requires S256 "when technically capable" (every client this server targets is), and the alternative method, "plain", sends the verifier itself as the challenge — accepting it would mean the value that protects the authorization code is the same value an eavesdropper on the redirect already saw. Refusing "plain" outright, rather than merely preferring S256, is what makes that refusal a guarantee instead of a client-side courtesy.
Types ¶
type AuthCode ¶
type AuthCode struct {
ClientID string
RedirectURI string
Scopes []string
Resource string
CodeChallenge string
CodeChallengeMethod string
}
AuthCode is a single-use authorization code, consumed at the token endpoint.
type AuthorizationServerMetadata ¶
type AuthorizationServerMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
ScopesSupported []string `json:"scopes_supported"`
ResponseTypesSupported []string `json:"response_types_supported"`
GrantTypesSupported []string `json:"grant_types_supported"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
}
AuthorizationServerMetadata is served at /.well-known/oauth-authorization-server, per RFC 8414.
AuthorizationEndpoint deliberately names a different host than everything else in this document: it is the one endpoint a human's browser loads, so it points at the private, tailnet-only consent listener (LECTERN_OAUTH_AUTHORIZE_BASE), while registration, token issuance and revocation — which only the client's backend ever calls — stay on the public base this document itself is served from. Nothing in RFC 8414 requires same-origin endpoints; MCP clients follow the URLs given, not the issuer's host.
type Client ¶
type Client struct {
ID string
Name string
RedirectURIs []string
AuthMethod string // "none" (public/PKCE-only) or "client_secret_post"
Created time.Time
}
Client is an OAuth client registered via Dynamic Client Registration.
type ClientSummary ¶
type ClientSummary struct {
ID string
Name string
RedirectURIs []string
Created time.Time
LastUsed time.Time
ActiveTokens int
Scopes []string
}
ClientSummary is one row of the admin console's client list.
type Config ¶
type Config struct {
Store *Store
// PublicBase is the base URL of the tunnel — where claude.ai reaches this
// server. Everything except /oauth/authorize is served relative to it.
// The MCP resource this server protects is PublicBase + "/mcp".
PublicBase string
// AuthorizeBase is the base URL of the private, owner-only consent
// listener — reachable only from the tailnet (or loopback). Only
// /oauth/authorize lives here.
AuthorizeBase string
// Redirects bounds which hosts Dynamic Client Registration may claim.
// Nil uses DefaultRedirectPatterns.
Redirects *RedirectAllowlist
// Identity, when set, is asked who the caller is on every
// /oauth/authorize request.
Identity Identity
// AllowedLogins gates Identity's answer: only these logins may be
// treated as the owner. Required for the Tailscale fast-path to ever
// fire; empty means every consent goes through the admin-token form.
AllowedLogins []string
// AdminToken gates both the admin-token consent fallback and the
// client-management API. Normally LECTERN_OAUTH_ADMIN_TOKEN (falls back
// to LECTERN_AUTH_TOKEN — see cmd/lectern/mcp_http.go), sent as
// X-Lectern-Admin.
AdminToken string
}
Config is what an operator provides; Handler is what New derives from it.
type Handler ¶
type Handler struct {
Config
Resource string // canonical MCP resource URI: PublicBase + "/mcp"
// contains filtered or unexported fields
}
Handler serves both the public and the private OAuth surfaces. Which routes it answers depends only on which ServeMux it is registered into — see RegisterPublic / RegisterPrivate — never on where the process bound a socket, so a misconfigured bind cannot accidentally expose /oauth/authorize to the internet.
func (*Handler) PrivateMux ¶
PrivateMux is RegisterPrivate on a fresh mux.
func (*Handler) PublicMux ¶
PublicMux is RegisterPublic on a fresh mux, for standalone use and tests. A request for /oauth/authorize against this mux gets ServeMux's ordinary 404 — there is no handler for it here, which is what makes "the public listener refuses /oauth/authorize" true by construction rather than by a check somebody could forget.
func (*Handler) RegisterPrivate ¶
RegisterPrivate mounts the surface only the owner's own browser should ever load: the consent page, and the small client-management console.
func (*Handler) RegisterPublic ¶
RegisterPublic mounts the surface reachable from claude.ai's cloud: discovery metadata, registration, token issuance and revocation. Deliberately NOT /oauth/authorize — see RegisterPrivate.
type Identity ¶
Identity resolves who is approving a consent request, for one HTTP request against the private /oauth/authorize listener. login is a stable identity string (e.g. a Tailscale login name); ok is false when the caller could not be identified at all. cmd/lectern wires this to Lectern's own internal/auth tailnet-identity code (tailscaled's LocalAPI whois) rather than this package introducing a second one — see cmd/lectern/mcp_http.go.
type Owner ¶
Owner is who is trusted to approve a consent request. Lectern's web connector OAuth server has exactly one owner concept — this gates one person's board, not an accounts system — so Owner is a yes/no plus a display name, not a role.
type ProtectedResourceMetadata ¶
type ProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ResourceName string `json:"resource_name,omitempty"`
}
ProtectedResourceMetadata is served at /.well-known/oauth-protected-resource, per RFC 9728. It is the document a client fetches after the MCP endpoint answers a bare request with 401 — see the resource_metadata parameter on the WWW-Authenticate header, set in internal/mcp/http.go.
type RedirectAllowlist ¶
type RedirectAllowlist struct {
// contains filtered or unexported fields
}
RedirectAllowlist bounds which hosts Dynamic Client Registration may claim a redirect_uri on.
This is a HOST allowlist, not a hardcoded exact-path allowlist, on purpose. Neither Anthropic nor OpenAI publishes a stable, versioned callback PATH for their web connector OAuth flow — community write-ups quote paths like "https://claude.ai/api/mcp/auth_callback", but nothing commits to one, and a wrong guess here would either lock out a legitimate connector or (worse) be copied verbatim into a security control. Binding to the HOST instead is both safer and more correct: Dynamic Client Registration is exactly the mechanism that lets the client tell us its real redirect_uri at connect time, so the server's job is bounding WHO may register (a small set of trusted hosts) rather than guessing WHERE they redirect to today. /oauth/authorize then holds each client to the exact URI it registered — see server.go — so the host allowlist is the outer gate and exact match is the inner one.
func NewRedirectAllowlist ¶
func NewRedirectAllowlist(patterns []string) *RedirectAllowlist
NewRedirectAllowlist builds an allowlist from scheme://host patterns. A pattern's host may start with "*." to match any subdomain (but not the bare apex — list both explicitly, as DefaultRedirectPatterns does).
func (*RedirectAllowlist) Allowed ¶
func (a *RedirectAllowlist) Allowed(rawURI string) bool
Allowed reports whether rawURI may be registered as a redirect_uri.
Independent of the pattern match, OAuth 2.1's communication-security requirement is enforced directly: a redirect URI must be either "localhost"/"127.0.0.1"/"::1" or use https. A pattern list that somehow contained a bare-http non-loopback entry could not override that.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the web connector's OAuth state: registered clients, live authorization codes, and issued access/refresh tokens. One process, one file, one writer — sized for the volume this actually sees (a handful of connectors, not a multi-tenant SaaS).
func (*Store) CheckClientSecret ¶
CheckClientSecret verifies a client_secret in constant time. A public client (AuthMethod "none") has no secret to check and this always fails for one — callers must not call it for a public client.
func (*Store) ConsumeAuthCode ¶
ConsumeAuthCode looks up and deletes a code atomically — a code redeemed twice is exactly the replay OAuth 2.1's authorization-code protection exists to prevent, so "read" and "invalidate" are one critical section under the store's write lock.
func (*Store) CreateClient ¶
func (s *Store) CreateClient(name string, redirectURIs []string, authMethod string) (*Client, string, error)
CreateClient registers a client. secret is returned once, in plaintext — the store only ever holds its hash.
func (*Store) IssueTokenPair ¶
func (s *Store) IssueTokenPair(clientID string, scopes []string, resource string) (*TokenPair, error)
IssueTokenPair mints an access token and a refresh token bound to the same client, scope and resource, sharing a family id so a later rotation can be traced back to the grant that started it.
func (*Store) ListClients ¶
func (s *Store) ListClients() ([]ClientSummary, error)
ListClients returns every registered client with its most recent token activity, newest first.
func (*Store) LookupAccessToken ¶
func (s *Store) LookupAccessToken(raw string) (*TokenRecord, error)
LookupAccessToken resolves a bearer token to what it may do, and records that it was used.
func (*Store) RevokeClient ¶
RevokeClient deletes every token — access and refresh — issued to a client. This is the admin console's Revoke button: it does not delete the client registration, so the connector's next attempt lands back on the consent page rather than a registration error that just invites it to re-register under a new client_id.
func (*Store) RevokeToken ¶
RevokeToken deletes a token, whichever kind it is. Per RFC 7009, an unknown token is not an error — the caller (server.go) always answers 200.
func (*Store) RotateRefresh ¶
RotateRefresh redeems a refresh token for a new token pair and revokes the one presented, so a stolen refresh token stops working the moment its legitimate owner's client next refreshes — the reuse-detection half of OAuth 2.1's refresh-token rotation requirement.