Quick start (llms.txt)
Authentication and authorization for Go services, for users and for AI agents, self-hosted in your database: user sign-in (password, MFA, sessions, organizations, RBAC, passwordless, passkeys, social, SSO, SCIM), API keys, an OAuth 2.1 / OpenID Connect provider, agents as first-class principals (grants, budgets, approvals, signed receipts, kill switch) and MCP protection. One import, a few lines, net/http.
Module: github.com/univeros/polaris.go (Go 1.26): go get github.com/univeros/polaris.go.
The package name is polaris.
Quickstart (copy this)
Section titled “Quickstart (copy this)”import ( polaris "github.com/univeros/polaris.go" "github.com/univeros/polaris.go/store" "github.com/univeros/polaris.go/store/sqlstore")
db, err := sqlstore.Open(ctx, store.Postgres, os.Getenv("DATABASE_URL")) // or store.MySQL, store.SQLitecfg, err := polaris.FromEnv(db /*, plugins... */) // reads the env vars belowp, err := polaris.New(cfg) // validates everything; errors say how to fix_, err = p.Migrate(ctx) // creates missing tables, seeds permissions; idempotent
mux := http.NewServeMux()mux.Handle("/", p.Handler()) // every Polaris route: /auth/register, /auth/login, /auth/token/refresh, /orgs, ...mux.Handle("GET /api/invoices", p.Protect(invoicesHandler, "org.read")) // your route, Polaris principals// in the handler: who, ok := polaris.PrincipalFrom(r.Context()) — who.UserID, who.OrganizationID,// who.Permissions, who.Kind (polaris.KindUser | KindAPIKey | KindOAuthClient | KindAgent), who.Delegated.Environment: APP_KEY (≥ 32 bytes: openssl rand -base64 32), AUTH_JWT_PRIVATE_KEY and
AUTH_JWT_PUBLIC_KEY (PEM; openssl genrsa -out jwt.key 2048 && openssl rsa -in jwt.key -pubout -out jwt.pub),
AUTH_ISSUER (your public base URL). Optional: AUTH_AUDIENCE, AUTH_JWT_PREVIOUS_PUBLIC_KEY (key
rotation), AUTH_ACCESS_TOKEN_DENYLIST, … — every option is in package config (go doc config.Auth).
EdDSA instead of RS256: polaris keys:generate --alg=EdDSA (base64 keys for the same two variables), then
cfg.Auth.AccessToken.Signer = config.SignerEdDSA before polaris.New; the JWKS publishes it as an OKP key.
Local development without them: call polaris.DevEnv("http://localhost:8080") before FromEnv and run
with POLARIS_DEV=1; it generates the missing ones (throwaway, logged as warnings) and refuses to run
without that variable, so production never boots on them.
Your own permissions: cfg.Permissions = map[string]string{"invoices.read": "Read invoices"} before
polaris.New; Migrate adds them to the catalog. Only what you hold can be granted, so say which
system roles hold them: cfg.RolePermissions = map[string][]string{"owner": {"invoices.read"}}
(“owner”, “admin” or “member”; every organization’s copy of that role, existing ones on the next
Migrate). An owner then puts them into custom roles through POST /orgs/{id}/roles, invitations
and API keys.
Databases: PostgreSQL 17 and MySQL 8.4 (every suite runs on both in CI), and SQLite through the bundled
pure-Go driver (modernc.org/sqlite, SQLite 3.54; no cgo); other versions are untested. On MySQL,
sqlstore.Open sets clientFoundRows=true; a pool you open yourself for sqlstore.New needs it too. Migrate creates missing tables and adds
missing columns and indexes; it never drops a column or changes a type (polaris schema:diff lists
those). db.Close() closes the pool.
Housekeeping: schedule p.Prune(ctx) (hourly is plenty) to delete expired refresh tokens, codes and
invitations; idempotent on every replica.
Production ports (fields of polaris.Config; each has a working default, the logging ones warn):
Mailer notify.Mailer and SMS notify.SMSSender (verification / reset / OTP delivery — the
defaults only log), Cache cache.Cache and RateStore (share across replicas; a host cache must make
Add atomic, e.g. Redis SET NX), Events event.Dispatcher, Logger *slog.Logger, PathPrefix.
Host extensions: Listeners []event.Listener (your listeners on every domain event; package event
names them: event.UserRegistered, event.MemberInvited, …), Middleware (wrapped outermost around
Handler and every Protect: tracing, request ids; p.Wrap(h) puts it around your other routes),
Hooks (below).
Your app’s own data: hooks, transactions, Go calls
Section titled “Your app’s own data: hooks, transactions, Go calls”cfg.Hooks = polaris.Hooks{ OnUserCreated: func(ctx context.Context, u polaris.User) error { // runs in the account's transaction _, err := db.Conn(ctx).ExecContext(ctx, "INSERT INTO profiles (user_id) VALUES ($1)", u.ID) // ? on MySQL and SQLite return err }, OnUserDeleted: func(ctx context.Context, userID string) error { return deleteProfile(ctx, userID) }, Claims: func(ctx context.Context, in polaris.ClaimsInput) (map[string]any, error) { return map[string]any{"app_plan": planOf(in.UserID)}, nil // reserved names (sub, org, roles, …) are refused },}cfg.Listeners = []event.Listener{func(ctx context.Context, e event.Event) { if r, ok := e.(event.UserRegistered); ok { welcome(ctx, r.UserID) // inside db.Tx, only after the commit }}}p, err := polaris.New(cfg)
var ada polaris.Usererr = db.Tx(ctx, func(ctx context.Context) error { // your transaction: Polaris calls and db.Conn(ctx) join it var err error if ada, err = p.Users().Create(ctx, polaris.NewUser{Email: "[email protected]", EmailVerified: true}); err != nil { return err } _, err = db.Conn(ctx).ExecContext(ctx, "UPDATE profiles SET plan = $1 WHERE user_id = $2", "pro", ada.ID) return err // an error rolls back the account and its rows, and its events never go out (no mail)})org, err := p.Orgs().Create(ctx, ada.ID, "Acme", "") // ada is its ownererr = p.Orgs().AddMember(ctx, org.ID, otherUserID, "member")_, inviteToken, err := p.Orgs().Invite(ctx, org.ID, ada.ID, "[email protected]", "admin") // deliver it; POST /auth/invites/accept takes ittokens, err := p.Sessions().Issue(ctx, polaris.SignIn{UserID: ada.ID, OrganizationID: org.ID}) // your own sign-in, in org; works on Protectok := p.Can(ctx, polaris.Principal{UserID: ada.ID, OrganizationID: org.ID}, "org.read")mux.Handle("GET /healthz", p.Wrap(health)) // Config.Middleware around a route Protect does not guard// errors: errors.Is(err, polaris.ErrNotFound), polaris.ErrConflict, polaris.ErrForbidden, polaris.ErrEmailNotVerified, polaris.ErrInvalidInput, polaris.ErrInvalidCredentialsp.Users(): Get, ByEmail, Create, Import, SetPassword, Disable, Enable, Delete. p.Orgs(): Create, Get,
ListFor, AddMember, SetRoles, RemoveMember, Invite. p.Sessions(): Issue, Refresh, Revoke, RevokeAll. Same
rules, events and audit as the HTTP routes; the caller is trusted (no permission check; an
invitation’s roles stay within its inviter’s). Sessions().Issue refuses an unverified email with
ErrEmailNotVerified (also ErrForbidden) while Auth.Flows.RequireVerifiedEmail is on (the
default): create accounts you verified yourself with NewUser.EmailVerified. Events reach listeners
in two phases. Listeners that write to the database run inside the transaction that raised the
event and commit or roll back with it: Polaris’s audit trail and erasure, and your
cfg.TxListeners (write with db.Conn(ctx)). cfg.Listeners and the mail run after the commit
and never after a rollback (mail, webhooks, queues); db.AfterCommit(ctx, fn) does the same for
your own side effects. Your own *sql.Tx (an ORM’s) joins with sqlstore.WithTx(ctx, tx), but
Polaris cannot see that commit, so there cfg.Listeners and the mail run before you commit.
Migrating your users
Section titled “Migrating your users”Bring existing accounts with the password hash they have; nobody resets a password. The first successful sign-in of each user replaces the imported hash with Argon2id.
tx, err := db.DB().BeginTx(ctx, nil)for _, row := range legacyRows { // your users table, or an Auth0 / Firebase / Django export _, err = p.Users().Import(sqlstore.WithTx(ctx, tx), polaris.ImportedUser{ Email: row.Email, PasswordHash: row.PasswordHash, DisplayName: row.Name, EmailVerified: row.Verified, Disabled: row.Banned, CreatedAt: row.CreatedAt, }) // ErrInvalidInput (and security.ErrUnsupportedHash): a hash Polaris cannot verify; ErrConflict: email taken}err = tx.Commit() // all or nothing; OnUserCreated ran for each account, no email was sentHashes verified as they are (security.SupportedHashFormats): bcrypt $2a$/$2b$/$2y$ (Auth0,
Devise, Laravel, most Go and Node apps), Argon2id/Argon2i, Django pbkdf2_sha256$… and scrypt$…,
passlib $pbkdf2-sha256$, $pbkdf2-sha512$, $scrypt$ln=…. Firebase: build
fmt.Sprintf("$firebase-scrypt$ln=%d,r=%d,sep=%s,key=%s$%s$%s", memCost, rounds, saltSeparator, signerKey, salt, passwordHash)
from the project’s hash parameters and each exported user (base64 values as exported). A cost
outside sane bounds is refused. Cognito exports no hashes: import without PasswordHash and let
users reset, or verify them your way and call p.Sessions().Issue. Another scheme of your own: wrap
security.Argon2id as Config.Hasher, handling your prefix in Verify and CheckHash (go doc security.HashChecker); it upgrades on sign-in the same way.
Plugins (pass to polaris.FromEnv / Config.Plugins)
Section titled “Plugins (pass to polaris.FromEnv / Config.Plugins)”plugins/audit—audit.New(audit.Config{}): append-only audit log of every event, sinks, drains, hash chain. Required by admin.plugins/admin—admin.New(admin.Config{}): operator API (/admin/*) for users, sessions, MFA, orgs, audit; operator keyspak_.plugins/apikeys—apikeys.New(apikeys.Config{}): user/org API keys (pk_live_…,Authorization: Bearerorx-api-key), scoped to a subset of the owner’s permissions, rate-limited, rotatable.plugins/oauth—oauth.New(oauth.Config{}): OAuth 2.1 / OIDC provider (PKCE, refresh rotation, client credentials, device, CIBA, token exchange withact, DPoP, DCR, CIMD, discovery). Scopes are permissions.plugins/agents—agents.New(agents.Config{Capabilities: …}): agents as principals. Needsoauth.plugins/mcp—mcp.New(mcp.Config{BaseURL: …}): Polaris as an MCP server (POST /mcp, stdio); andmcp.Protectfor your own MCP servers.plugins/passwordless—passwordless.New(passwordless.Config{RedirectURIs: …}): magic links, email / phone codes, one-time hand-off tokens; all behind core’s MFA gate.plugins/username—username.New(username.Config{}): case-insensitive usernames; sign in with username or email.plugins/anonymous—anonymous.New(anonymous.Config{OnConvert: …}): guest sessions converted on sign-up.plugins/multisession—multisession.New(multisession.Config{}): several accounts per device, switch without signing in again.plugins/social—social.New(social.Config{Providers: map[string]social.Provider{"google": {ClientID: …, ClientSecret: …}}}): 19 OAuth/OIDC providers + generic, linking, One Tap.plugins/passkey—passkey.New(passkey.Config{RPID: "example.com", Origins: []string{"https://example.com"}}): WebAuthn sign-in; a passkey is also an MFA factor.plugins/messaging—messaging.New(messaging.Config{Email: &messaging.SMTP{…}, SMS: &messaging.Twilio{…}}): becomes core’s mailer and SMS sender; templates per instance/org, translations, send caps.plugins/sentinel—sentinel.New(sentinel.Config{}): risk engine on sign-up, sign-in, reset and code sends (captcha, breached passwords, disposable domains, velocity, geo via yourGeoResolver); observes by default,Mode: sentinel.Enforceblocks and challenges.plugins/sso—sso.New(sso.Config{}): SAML 2.0 and OIDC sign-in per organization, verified domains, single logout; an IdP signs in only the accounts its organization provisioned or whose email domain it verified, and the session stays in that organization (no switch-org, no account-level routes;Principal.OrganizationBound). Offline (tests, a laptop):sso.Config{HTTPClient: http.DefaultClient, Domains: yourVerifier}, a client that reaches your local IdP (the default reaches public addresses only) and ansso.DomainVerifierthat proves your test domain; leave both unset in production.plugins/scim—scim.New(scim.Config{}): SCIM 2.0 provisioning per organization with an org-managed connection token; changes global accounts only when the connection created them.plugins/ui—ui.New(ui.Config{AppName: "Acme", AfterSignIn: "/dashboard"}): server-rendered sign-in, MFA, sign-up, verification, reset, sign-out and OAuth consent / device pages under/auth/ui(no JavaScript);web.RequireSignIn(p.Protect(h))for your pages.
Agents: declare what agents may do
Section titled “Agents: declare what agents may do”ag := agents.New(agents.Config{Capabilities: []agents.Capability{ {Name: "invoices.list", Description: "List invoices", Permission: "org.read", Risk: agents.RiskLow, Handler: func(ctx context.Context, call agents.Call) (any, error) { return listInvoices(ctx, call.Agent) }}, {Name: "refund", Description: "Refund an invoice", Permission: "billing.refund", Risk: agents.RiskHigh, Location: "https://app.example.com/api/refunds", Input: map[string]any{"type": "object", "required": []string{"invoice_id"}, "properties": map[string]any{"invoice_id": map[string]any{"type": "string"}}}},}})cfg, _ := polaris.FromEnv(db, audit.New(audit.Config{}), admin.New(admin.Config{}), oauth.New(oauth.Config{}), ag)cfg.Permissions = map[string]string{"billing.refund": "Refund an invoice"} // your own permissions; Migrate seeds themcfg.RolePermissions = map[string][]string{"owner": {"billing.refund"}} // owners hold it, so they can approve itp, _ := polaris.New(cfg)mux.Handle("/", p.Handler()) // includes /.well-known/agent-configuration, /agents/*, /oauth2/*mux.Handle("POST /api/refunds", ag.Protect("refund", refundHandler)) // grant, constraints, budget checked BEFORE refundHandler// in refundHandler: call, _ := agents.CallFrom(r.Context()); the response gets X-Polaris-Receipt.Behind ag.Protect the arguments are the JSON body: a query, or a body of any other Content-Type, is refused.
Risk tiers set the approval strength (low/medium: session, high: step-up). Low-risk grants are
auto-approved with a budget of 100 by default (Config.AutoApprove). Every execution writes a signed,
hash-chained receipt; POST /agents/{id}/revoke is the kill switch.
Agent Auth Protocol clients (@auth/agent): Config.Discovery: agents.DiscoveryAgentAuth serves the
protocol’s document at /.well-known/agent-configuration; the default, agents.DiscoveryPolaris, serves
Polaris’s, which is always at GET /agents/configuration too (the Go agent SDK falls back to it).
The protocol’s routes (/capability/list, /capability/describe, /agent/register, /agent/status,
/agent/request-capability, /capability/execute) are served in both modes. A client signs in through a
host its owner registered (POST /agents/hosts with public_key, the host’s Ed25519 JWK, and proof, signed by that key:
agent.SignHostLink), or, with
DiscoveryAgentAuth, through one the server does not know: a signed-in person types the code the client
shows at your ApprovalURL page (GET /agents/approvals/code, POST /agents/approvals/{id}/decide) and the
host and the agent become theirs. In that mode approvals need a recent sign-in, and a passkey for medium (the default) and high risk: add the
passkey plugin or set Config.Strengths, or the server does not start. At a capability’s Location, Protect and Guard read
such a client’s {capability, arguments} and answer {data}. Config.RateLimits bounds these routes, Config.Lifetimes how
long such agents live. A resource server introspects an agent’s JWT (POST /agent/introspect) as a trusted OAuth client.
Config.DisableDynamicHosts turns unknown hosts off; schedule ag.Prune(ctx).
Agents: sign in from Go (the agent side)
Section titled “Agents: sign in from Go (the agent side)”import "github.com/univeros/polaris.go/agent"
key, _ := agent.GenerateKey(agent.EdDSA) // persist key.Export(); reload with agent.ImportKeya, _ := agent.New(ctx, "https://app.example.com", agent.WithKey(key))bot, _, err := a.Enroll(ctx, enrollmentToken, agent.Registration{Name: "Worker", Mode: agent.Delegated})asked, _ := bot.RequestGrants(ctx, agent.GrantRequest{Capabilities: []agent.CapabilityRequest{{Name: "refund"}}})if asked.Approval != nil { _, err = bot.WaitForApproval(ctx, *asked.Approval) } // a person approvesres, err := bot.Execute(ctx, "invoices.list", nil) // signed request JWT per call; res.Receipt// errors: errors.Is(err, agent.ErrCapabilityNotGranted), agent.ErrBudgetExhausted, agent.ErrApprovalDenied …Protect any Go MCP server with Polaris tokens
Section titled “Protect any Go MCP server with Polaris tokens”h, err := mcp.Protect(mcpServerHandler, mcp.ProtectConfig{ Resource: "https://tools.example.com/mcp", Issuer: "https://auth.example.com", JWKSURL: "https://auth.example.com/auth/.well-known/jwks.json", Scopes: []string{"tools.use"},})mux.Handle("/", h) // also serves /.well-known/oauth-protected-resource/mcp; mcp.Claims(ctx) in the handlerMiddleware shape, optional sign-in, requirements
Section titled “Middleware shape, optional sign-in, requirements”mux.Handle("GET /", p.Authenticate(home)) // anonymous or signed in; a bad or revoked token is still 401mux.Handle("GET /api/invoices", p.Require("invoices.read")(list)) // the same as p.Protect(list, "invoices.read")mux.Handle("POST /api/billing", p.Require()(polaris.RequireKind(polaris.KindUser)(billing))) // people only: no API keys, OAuth clients, agentsmux.Handle("GET /api/team", p.Require()(polaris.RequireOrganization(team))) // 403 without an active organizationp.Authenticate and p.Require(...) are func(http.Handler) http.Handler: chi’s r.Use(p.Authenticate)
then r.With(p.Require("org.read")) verifies the credential once per request.
Verify Polaris tokens in another Go service
Section titled “Verify Polaris tokens in another Go service”import "github.com/univeros/polaris.go/verify"
v, err := verify.New(verify.Config{ Issuer: "https://auth.example.com", // the Polaris host's AUTH_ISSUER JWKSURL: "https://auth.example.com/auth/.well-known/jwks.json", // fetched, cached 1 h, refetched for a new kid})mux.Handle("GET /invoices", v.Require("invoices.read")(invoicesHandler)) // 401 / 403 / 503 (issuer unreachable)// in the handler: c, _ := verify.ClaimsFrom(r.Context()) — c.Subject, c.OrganizationID, c.Scopes, c.Allclaims, err := v.Verify(ctx, rawToken) // a token from elsewhere (WebSocket, queue); errors.Is(err, verify.ErrInvalidToken)No database: it checks the signature (RS256 or EdDSA), typ, iss, aud, exp and nbf only. It cannot
see a sign-out, a revoked token, a disabled user or changed permissions until the token expires
(AUTH_ACCESS_TOKEN_TTL, 15 min by default): route actions that must see those through the host’s
p.Protect. Audiences: []string{"https://billing.example.com"} accepts OAuth tokens issued for
that resource (and only tokens with that aud). The default HTTP client reaches public addresses
only; pass HTTPClient for an issuer on a private network.
Testing your app
Section titled “Testing your app”srv := polaristest.New(t, polaristest.WithPlugins(audit.New(audit.Config{}))) // SQLite in a temp dir, test keys, recorders// srv.Handler(), srv.Users(), srv.Sessions(), srv.Mailer.Sent() (verification tokens), srv.SMS, srv.Events.Names()// polaristest.WithConfig(func(c *polaris.Config) { c.Hooks = … }) for anything elsecfg.Hasher = polaristest.Hasher() // tests that build their own polaris.Config: cheap Argon2id, fast under -racego run ./cmd/polaris <command> — every command idempotent, --json for one JSON object,
exit 1 (failed) / 2 (bad usage) with a remedy: line.
polaris init [--plugins=audit,admin,apikeys,oauth,agents,mcp,…] # writes .env: APP_KEY, RS256 pair, AUTH_ISSUER; prints the quickstartpolaris migrate --plugins=… # DATABASE_URL or --dsn (postgres://, mysql://, sqlite:, file:)polaris doctor --plugins=… # secrets, keys, manifest, connectivity, schema; each check with its fixpolaris schema:export --target=sql:postgres|sql:mysql|sql:sqlite schema:diff schema:drop --forcepolaris manifest --format=json|openapi keys:generate mcp (stdio MCP server)polaris audit:prune|audit:verify admin:grant <email> <role> admin:key <name> <role> anonymous:pruneWith your own plugins, build your own binary: os.Exit(cli.Run(ctx, p, os.Args[1:], os.Stdout, os.Stderr)).
Errors
Section titled “Errors”Core routes answer {"error": "<code>", "message": "…"}; plugin routes answer RFC 9457 problems
(application/problem+json, type = https://polaris.univeros.io/problems/<plugin>/<name>).
Go calls on *polaris.Polaris return polaris.ErrNotFound, ErrConflict, ErrForbidden,
ErrInvalidInput, ErrInvalidCredentials (errors.Is); other packages have their own sentinels.
Where to look
Section titled “Where to look”examples/— complete programs (those with a README run with no setup butPOLARIS_DEV=1 go run ./examples/<name>, SQLite and keys generated at start bypolaris.DevEnv; the README has the curl walkthrough with real output;main_test.gokeeps it working;minimal,api-keysandwebappread the environment above):minimal(core, one protected route),api-keys,webapp(server-rendered pages withplugins/ui),agents(capabilities in process and behindag.Protect, an agent built with packageagent: enrol, grants, approval, budget and constraint refusals, receipts, kill switch),mcp(your MCP server behindmcp.Protect, Polaris’s/mcp, token exchange per resource),b2b(organizations, your permissions, roles, invitations, org API keys, audit, admin, SSO and SCIM setup),signin-methods(magic link, email code, username, guest conversion, multisession, passkey, social OIDC, messaging, sentinel, MFA),hooks(your own table kept in step byHooks,Claims, listeners, middleware andp.Wrap, a host transaction withdb.Txanddb.Conn,Prune).plugins/<id>/README.md— per plugin: config, routes, events, permissions, problems, hooks.plugins/agents/example_test.go,agent/example_test.go,plugins/mcp/example_test.go— runnable agent flows.go doc github.com/univeros/polaris.go/<package>— every exported identifier is documented.internal/apispec/api/**.yaml— every route: method, path, auth, permissions, input, output, errors.API.md— the Go API promise: every exported name outsideinternal/(the host surface, the plugin SDK, the ports), and the deprecation policy.docs/decisions.md— every design decision, with the reason.