core

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package core holds the identifiers, domain types, errors and cross-package interfaces of MCP Gatekeeper.

It is frozen (docs/PLAN.md §4.1). Agents never edit it: a change request goes in the agent's report, and the orchestrator merges it between waves.

The types came from Family Hub's internal/core. The one rename: a module became a resource, because an application decides what an MCP endpoint stands for (Family Hub: one module; Homie: the whole home).

Index

Constants

View Source
const (
	PrefixAccount = "acc"
	PrefixPerson  = "per"
	PrefixPasskey = "pk"
	PrefixInvite  = "inv"
	PrefixGrant   = "grt"
	PrefixClient  = "cli"
	PrefixTxn     = "txn"
)

Prefixes for NewID.

View Source
const PermissionAll = "all"

PermissionAll is the permission id for everything an application offers, now and later. An owner has it.

Variables

View Source
var (
	ErrNotFound       = errors.New("not found")
	ErrConflict       = errors.New("conflict")
	ErrExpired        = errors.New("expired")
	ErrUsed           = errors.New("already used")
	ErrNoSession      = errors.New("no session")
	ErrStepUpRequired = errors.New("step-up required")
	ErrForbidden      = errors.New("forbidden")
	ErrInvalidToken   = errors.New("invalid token")
)

Errors shared by the packages; wrap them with %w.

Functions

func ClientIP

func ClientIP(r *http.Request, mode ClientIPMode) string

ClientIP returns the client address of r under mode, falling back to the TCP peer.

The application must make sure only a trusted peer can set the header that mode reads (Family Hub deletes CF-Connecting-IP and X-Forwarded-For from any peer outside its edge network before this runs). A request without the header falls back to the TCP peer: in a header mode only the trusted connector should reach the listener (a local connector: listen on loopback only), or every such request shares one address.

func NewID

func NewID(prefix string) string

NewID returns prefix + "_" + 16 random lower-case base32 characters (80 bits).

func WithViewer

func WithViewer(ctx context.Context, v Viewer) context.Context

WithViewer returns ctx carrying v.

Types

type AccessInfo

type AccessInfo struct {
	GrantID    GrantID
	PersonID   PersonID
	AccountID  AccountID
	ResourceID ResourceID
	ClientID   ClientID
	Assistant  Assistant
	Scope      string
	ExpiresAt  time.Time
}

AccessInfo is what a valid access token stands for.

type Account

type Account struct {
	ID        AccountID
	Name      string
	CreatedAt time.Time
}

Account is one family or household. Application data is kept per account.

type AccountID

type AccountID string

AccountID names an account: one family or one household.

type Assistant

type Assistant string

Assistant is the AI product behind an OAuth client.

const (
	AssistantChatGPT Assistant = "chatgpt"
	AssistantClaude  Assistant = "claude"
)

Assistants the gatekeeper accepts.

type AuditEntry

type AuditEntry struct {
	ID        string // assigned by the store; newer entries sort after older ones
	At        time.Time
	AccountID AccountID // empty: a system event
	Actor     PersonID  // empty: the CLI or the system
	Action    string    // dotted, e.g. "auth.login", "module.deploy"
	Target    string
	Detail    map[string]string
	IP        string
}

AuditEntry is one line of the audit log. Detail never holds secrets or application data.

type AuthCode

type AuthCode struct {
	CodeHash      []byte
	GrantID       GrantID
	ClientID      ClientID
	RedirectURI   string
	Resource      string
	Scope         string
	CodeChallenge string
	CreatedAt     time.Time
	ExpiresAt     time.Time
}

AuthCode is a one-time authorization code. Only its sha256 is stored.

type Brand

type Brand struct {
	Product       string // shown in passkey prompts and pages, e.g. "Family Hub"
	SessionCookie string // e.g. "__Host-fh_session"; must start with "__Host-"
	TxnCookie     string // the consent-transaction binding cookie, e.g. "__Host-fh_txn"; must start with "__Host-"
	CSRFHeader    string // e.g. "X-Family-Hub"; every mutating /api call must send it with the value "1"

	// ResourceNoun and AppNoun name, in the texts assistants and people read, what one MCP endpoint serves and the
	// application itself. Empty means Family Hub's words, "module" and "hub", so its texts keep their bytes; read them
	// through ResourceWord and AppWord.
	ResourceNoun string
	AppNoun      string
}

Brand holds the application-specific names the gatekeeper puts on the wire. Changing one of them for a running application signs everybody out (cookies) or breaks old browser tabs (header), so an application keeps its values.

func (Brand) AppWord added in v0.2.0

func (b Brand) AppWord() string

AppWord returns AppNoun, or "hub" when it is empty.

func (Brand) ResourceWord added in v0.2.0

func (b Brand) ResourceWord() string

ResourceWord returns ResourceNoun, or "module" when it is empty.

type ClientID

type ClientID string

ClientID is an OAuth client_id: an id issued by DCR or, for CIMD, the URL of the metadata document.

type ClientIPMode

type ClientIPMode string

ClientIPMode says where the client address of a request comes from.

const (
	ClientIPCloudflare ClientIPMode = "cf-connecting-ip" // behind cloudflared: the CF-Connecting-IP header
	ClientIPForwarded  ClientIPMode = "x-forwarded-for"  // behind one reverse proxy: the last X-Forwarded-For hop
	ClientIPRemote     ClientIPMode = "remote"           // no proxy: the TCP peer
)

Client address sources.

type ClientKind

type ClientKind string

ClientKind says how an OAuth client registered.

const (
	ClientDCR  ClientKind = "dcr"
	ClientCIMD ClientKind = "cimd"
)

Client kinds.

type Clock

type Clock func() time.Time

Clock returns the current time; tests pass a fake one.

type Grant

type Grant struct {
	ID         GrantID
	PersonID   PersonID
	AccountID  AccountID
	ClientID   ClientID
	ResourceID ResourceID
	Scope      string
	CreatedAt  time.Time
	LastUsedAt *time.Time
	RevokedAt  *time.Time
}

Grant is a consent: one person let one assistant client use one resource. Revoking it revokes its tokens.

type GrantID

type GrantID string

GrantID names one consent: a person, an assistant's client and a resource.

type Invite

type Invite struct {
	ID        string
	TokenHash []byte
	Kind      InviteKind
	AccountID AccountID // empty for InviteSetup
	Name      string    // the person's name as the inviter typed it
	CreatedBy PersonID  // empty for InviteSetup
	CreatedAt time.Time
	ExpiresAt time.Time
	UsedAt    *time.Time
	RevokedAt *time.Time
	// AccessUntil and Permissions are copied to the person who redeems a member invite, in the same transaction (see
	// Person). ExpiresAt is the link's life; AccessUntil is the person's.
	AccessUntil *time.Time
	Permissions []string
}

Invite is a one-time link. Only the sha256 of the token is stored.

type InviteKind

type InviteKind string

InviteKind says what redeeming an invite creates.

const (
	InviteSetup  InviteKind = "setup"  // the first superadmin and their account (CLI only)
	InviteOwner  InviteKind = "owner"  // an owner: of a new account, or a co-owner of an existing one; by the superadmin
	InviteMember InviteKind = "member" // a member of an existing account, made by its owner
)

Invite kinds.

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware wraps a handler.

type OAuthClient

type OAuthClient struct {
	ID           ClientID
	Kind         ClientKind
	Assistant    Assistant
	Name         string
	RedirectURIs []string
	AuthMethod   string    // "none", "client_secret_post" or "client_secret_basic"
	SecretHash   []byte    // sha256 of the client secret; nil for "none"
	FetchedAt    time.Time // CIMD: when the metadata document was last fetched
	CreatedAt    time.Time
	LastUsedAt   *time.Time
}

OAuthClient is a registered assistant client.

type Passkey

type Passkey struct {
	ID           string
	PersonID     PersonID
	CredentialID []byte
	Data         []byte
	Name         string
	CreatedAt    time.Time
	LastUsedAt   *time.Time
}

Passkey is a stored WebAuthn credential. Data belongs to package auth (the credential as JSON).

type PerResource

type PerResource struct {
	Prefix string // ends with "/"
}

PerResource serves every resource under its own path: Prefix + id (Family Hub: Prefix "/mcp/").

func (PerResource) FromPath

func (p PerResource) FromPath(path string) (ResourceID, bool)

FromPath implements ResourcePaths.

func (PerResource) Path

func (p PerResource) Path(id ResourceID) string

Path implements ResourcePaths.

type PermissionCatalog added in v0.2.0

type PermissionCatalog interface {
	Permissions(ctx context.Context, a AccountID) ([]PermissionInfo, error)
}

PermissionCatalog lists the permissions an application offers in account a. An application that gives people permissions and access terms passes one to package people; without one, people refuses both, as Family Hub needs. The gatekeeper only checks ids against the catalog and stores them: enforcing them is the application's.

type PermissionInfo added in v0.2.0

type PermissionInfo struct {
	ID    string
	Title string
	Group string
}

PermissionInfo is one permission an application offers when a person is invited or changed (Homie: a device family). ID is what Person.Permissions holds, Title is what people read, and Group sorts the choices into sections.

type Person

type Person struct {
	ID         PersonID
	AccountID  AccountID
	Name       string
	Role       Role
	Superadmin bool // manages accounts and the application; never sees other accounts' data
	CreatedAt  time.Time
	DisabledAt *time.Time
	// AccessUntil ends the person's access at that instant (a guest's term); nil means no end. Only an application
	// that offers terms sets it (package people, with a PermissionCatalog).
	AccessUntil *time.Time
	// Permissions are application-defined ids of what the person may use (e.g. PermissionAll, "plugin:tv"); nil means
	// the application's default. The gatekeeper checks them against the application's PermissionCatalog and stores
	// them; it never interprets them.
	Permissions []string
}

Person is someone who signs in with a passkey. Every person belongs to exactly one account.

func (Person) Active added in v0.2.0

func (p Person) Active(now time.Time) bool

Active reports whether p may act at now: not disabled, and before the end of their term if they have one. Every check of a session, an access token, a refresh and a consent uses it.

type PersonID

type PersonID string

PersonID names a person.

type ResourceCatalog

type ResourceCatalog interface {
	// Resource returns a resource that can be connected right now, or ErrNotFound.
	Resource(ctx context.Context, id ResourceID) (ResourceInfo, error)
	// Available reports whether account a may use resource id now (Family Hub: the module is switched on for it).
	Available(ctx context.Context, a AccountID, id ResourceID) (bool, error)
}

ResourceCatalog tells the gatekeeper which MCP resources exist; the application implements it (Family Hub: its running modules; Homie: one resource, the home).

type ResourceID

type ResourceID string

ResourceID names what one MCP endpoint serves, chosen by the application (e.g. "notes", "home").

type ResourceInfo

type ResourceInfo struct {
	ID          ResourceID
	Name        string
	Description string
	Tools       []ToolInfo
}

ResourceInfo describes a resource for the OAuth metadata and the consent screen.

type ResourcePaths

type ResourcePaths interface {
	// Path returns the MCP path of a resource, e.g. "/mcp/notes" or "/mcp".
	Path(id ResourceID) string
	// FromPath returns the resource an MCP path belongs to: the path itself or anything below it.
	FromPath(path string) (ResourceID, bool)
}

ResourcePaths maps resources to their MCP paths on the Site and back.

type Role

type Role string

Role is a person's role inside their account.

const (
	RoleOwner  Role = "owner"
	RoleMember Role = "member"
)

Roles inside an account.

type RouteRegistrar

type RouteRegistrar interface {
	RegisterRoutes(mux *http.ServeMux)
}

RouteRegistrar adds a package's routes to the application's mux (Go 1.22 patterns, e.g. "POST /oauth/token").

type Session

type Session struct {
	IDHash      []byte
	PersonID    PersonID
	CreatedAt   time.Time
	LastSeenAt  time.Time
	ExpiresAt   time.Time // the absolute end
	StepUpUntil time.Time // zero when there is no fresh step-up
	UserAgent   string
}

Session is a browser session. Only the sha256 of the cookie value is stored.

type Sessions

type Sessions interface {
	// Viewer returns the signed-in person of r, or ErrNoSession.
	Viewer(r *http.Request) (Viewer, error)
	// RequireViewer runs, for mutating methods, the CSRF checks of docs/PLAN.md §4.4 first (403
	// {"error":"forbidden"}). Then: 401 {"error":"no_session"} without a session; otherwise it stores the Viewer in
	// the request context (read it with ViewerFrom) and calls next.
	RequireViewer(next http.Handler) http.Handler
	// RequireStepUp is placed after RequireViewer: 403 {"error":"step_up_required"} unless the session has a fresh
	// step-up.
	RequireStepUp(next http.Handler) http.Handler
	// SameOrigin runs only the CSRF checks of a mutating request (403 {"error":"forbidden"}).
	SameOrigin(next http.Handler) http.Handler
}

Sessions resolves browser sessions; package auth implements it.

type SingleResource

type SingleResource struct {
	At string // the path, e.g. "/mcp"
	ID ResourceID
}

SingleResource serves one resource at one path (Homie: At "/mcp", ID "home").

func (SingleResource) FromPath

func (s SingleResource) FromPath(path string) (ResourceID, bool)

FromPath implements ResourcePaths.

func (SingleResource) Path

Path implements ResourcePaths.

type Site

type Site struct {
	PublicURL string // "https://hub.example.com": no path, no trailing slash; also the OAuth issuer and the WebAuthn origin
	RPID      string // the WebAuthn relying party ID: the host of PublicURL
	ClientIP  ClientIPMode
}

Site says where the application is served. Every package that builds URLs or checks origins takes one.

func (Site) Validate added in v0.2.0

func (s Site) Validate() error

Validate reports whether s can be served (review GK-2):

  • PublicURL is https with a host and nothing after it; plain http only for localhost or a loopback address;
  • RPID, when set, is that host or a parent domain of it (package auth requires it to be set);
  • ClientIP is one of the known modes; an empty or unknown mode would silently mean the TCP peer, which behind a local connector is every client at once.

Every constructor that takes a Site calls it, so a mistake fails at start.

type Token

type Token struct {
	Hash      []byte
	GrantID   GrantID
	Kind      TokenKind
	Family    string // the refresh rotation family; reusing a rotated refresh token revokes the family
	CreatedAt time.Time
	ExpiresAt time.Time
	UsedAt    *time.Time // refresh tokens: when it was rotated
	RevokedAt *time.Time
}

Token is an opaque OAuth token. Only its sha256 is stored.

type TokenKind

type TokenKind string

TokenKind is access or refresh.

const (
	TokenAccess  TokenKind = "access"
	TokenRefresh TokenKind = "refresh"
)

Token kinds.

type TokenValidator

type TokenValidator interface {
	// ValidateAccess returns the access behind token if it is live and was issued for resource r; otherwise
	// ErrInvalidToken.
	ValidateAccess(ctx context.Context, token string, r ResourceID) (AccessInfo, error)
}

TokenValidator checks access tokens; package oauth implements it.

type ToolInfo

type ToolInfo struct {
	Name   string
	Title  string
	Access string // "read" or "write"
}

ToolInfo is one tool of a resource as the consent screen shows it.

type Viewer

type Viewer struct {
	Person  Person
	Account Account
	Session Session
}

Viewer is the signed-in person behind a request.

func ViewerFrom

func ViewerFrom(ctx context.Context) (Viewer, bool)

ViewerFrom returns the Viewer that WithViewer stored in ctx.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL