polaris

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 27 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.

README

Polaris

Polaris for Go

Authentication and authorization for Go services, for users and for AI agents.
Everything an auth system needs, self-hosted in your database, on net/http, with one import.

Go Reference CI Release Go version MIT license

Quick start · llms.txt · Plugins · AI agents · Documentation


Why Polaris

  • Complete. Accounts, MFA, sessions, organizations and roles, passwordless, passkeys, social sign-in, API keys, an OAuth 2.1 / OpenID Connect provider, SSO, SCIM, audit and risk scoring: the whole auth system, not a toolkit to assemble one.
  • Yours. Users live in your PostgreSQL, MySQL or SQLite database, next to your own tables. No hosted service, no per-user pricing, no data leaving your infrastructure.
  • Agents are first-class principals. An AI agent signs in with its own key, asks for grants a person approves, spends a budget, and leaves a signed, hash-chained receipt for every action. MCP servers take Polaris tokens.
  • Plain Go. An http.Handler for the auth routes, middleware for yours, context.Context everywhere, errors you match with errors.Is. polaristest gives your tests a server in one line.
  • Built to be integrated by coding agents. llms.txt is the whole integration on one page; every snippet in it is compiled by the test suite. Startup errors say how to fix them.
  • Careful where it matters. Argon2id, constant-time comparisons, rotating refresh tokens with reuse detection, fuzzed parsers, contract tests replaying every route, and a stable API checked on every pull request.

Quick start

go get github.com/univeros/polaris.go
go install github.com/univeros/polaris.go/cmd/polaris@latest
polaris init                      # writes .env: APP_KEY, an RS256 key pair, AUTH_ISSUER
set -a && . ./.env && set +a      # FromEnv reads the process environment
db, err := sqlstore.Open(ctx, store.Postgres, os.Getenv("DATABASE_URL"))
cfg, err := polaris.FromEnv(db) // APP_KEY, AUTH_JWT_*, AUTH_ISSUER; plugins go here too
p, err := polaris.New(cfg)      // validates everything; every error says how to fix it
_, err = p.Migrate(ctx)         // creates the missing tables; safe to run on every start

mux := http.NewServeMux()
mux.Handle("/", p.Handler()) // /auth/register, /auth/login, /auth/token/refresh, /orgs, …
mux.Handle("GET /api/invoices", p.Protect(invoicesHandler, "org.read"))

Inside your handler, the caller is one call away:

func invoices(w http.ResponseWriter, r *http.Request) {
	who, _ := polaris.PrincipalFrom(r.Context())
	fmt.Fprintf(w, "user %s in organization %s (%s)\n", who.UserID, who.OrganizationID, who.Kind)
}

p.Protect answers 401 without a principal and 403 without the permission. The principal can be a user, an API key, an OAuth client or an agent; the same check covers all of them. A complete program is in examples/minimal.

More complete programs, each one go run away with no setup and a curl walkthrough: agents (an AI agent end to end), mcp (your MCP server behind Polaris tokens), b2b (organizations, roles, invitations, API keys, SSO, SCIM), signin-methods (passwordless, passkeys, social, guests, MFA), hooks (your own tables, claims and transactions) and api-keys.

What you get

Area Included
Accounts Registration, email verification, password sign-in and reset (Argon2id, breached-password check), account disable, erase
MFA TOTP, SMS and email codes, recovery codes, step-up for sensitive routes
Sessions Short-lived JWTs (RS256 or EdDSA, JWKS published), rotating refresh tokens with reuse detection, cookie or body delivery, sign out everywhere
Organizations Multi-tenant organizations, members, invitations, roles and permissions resolved per request, your own permissions in the catalog
Your data Hooks in the account's transaction, your own JWT claims, a Go API (p.Users(), p.Orgs(), p.Sessions(), p.Can()) with the same rules as the routes
Migration p.Users().Import brings existing accounts with their password hashes (bcrypt, PBKDF2, scrypt; from your own table, Auth0, Firebase, Django, Devise, Laravel): no forced reset, upgraded to Argon2id on first sign-in (Migrating your users)
Operations OpenTelemetry traces and metrics, a CLI (init, migrate, doctor, schema:*, keys:generate), PostgreSQL, MySQL, SQLite

Plugins

Add what your service needs; each plugin brings its own tables, routes, permissions and events.

cfg, err := polaris.FromEnv(db,
	audit.New(audit.Config{}),
	admin.New(admin.Config{}),
	apikeys.New(apikeys.Config{}),
	passkey.New(passkey.Config{RPID: "example.com", Origins: []string{"https://example.com"}}),
)
Sign-in What it does
passwordless Magic links, email and phone codes, one-time hand-off tokens
passkey WebAuthn sign-in; a passkey is also an MFA factor
social 19 OAuth / OIDC providers and a generic one, account linking, Google One Tap
username Case-insensitive usernames; sign in with username or email
anonymous Guest sessions converted on sign-up
multisession Several accounts per device, switch without signing in again
ui Server-rendered sign-in, sign-up, MFA, verification, reset and OAuth consent pages; no JavaScript
Machines and agents What it does
apikeys User and organization API keys, scoped to a subset of permissions, rate-limited, rotatable
oauth OAuth 2.1 / OIDC provider: PKCE, client credentials, device, CIBA, token exchange, DPoP, dynamic registration
agents Agents as principals: grants, constraints, budgets, approvals, signed receipts, kill switch
mcp Polaris as an MCP server, and mcp.Protect for your own MCP servers
Enterprise and operations What it does
sso SAML 2.0 and OIDC per organization, verified domains, single logout
scim SCIM 2.0 provisioning per organization
admin Operator API for users, sessions, MFA, organizations and audit
audit Append-only audit log, sinks and drains, optional hash chain
sentinel Risk engine: captcha, breached passwords, disposable domains, velocity, geo
messaging Email and SMS delivery with templates, translations and send caps

AI agents

Declare what agents may do in your service; Polaris checks the grant, its constraints and budget before your handler runs, and signs a receipt after.

ag := agents.New(agents.Config{Capabilities: []agents.Capability{{
	Name:        "invoices.list",
	Description: "List invoices",
	Permission:  "org.read",
	Risk:        agents.RiskLow, // auto-approved, with a budget
	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, // a person approves, with step-up
	Location:    "https://app.example.com/api/refunds",
}}})

mux.Handle("POST /api/refunds", ag.Protect("refund", refundHandler))

The agent side is a Go SDK too:

key, _ := agent.GenerateKey(agent.EdDSA) // persist key.Export()
a, _ := 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 approves
}
res, err := bot.Execute(ctx, "invoices.list", nil) // res.Receipt is the signed receipt

Testing your app

func TestSignUp(t *testing.T) {
	srv := polaristest.New(t) // SQLite in a temp dir, test keys, recorded mail and SMS
	req := httptest.NewRequest("POST", "/auth/register",
		strings.NewReader(`{"email": "ada@example.com", "password": "correct horse battery staple"}`))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, req)
	if rec.Code != http.StatusAccepted || len(srv.Mailer.Sent()) != 1 {
		t.Fatalf("register: %d, %d mails", rec.Code, len(srv.Mailer.Sent()))
	}
}

srv.Handler() serves every route; srv.Mailer.Sent() holds the verification and reset emails; srv.Users() and srv.Sessions() set up state without HTTP; polaristest.WithPlugins(…) adds plugins.

Documentation

Read For
llms.txt The whole integration on one page: configuration, hooks, plugins, agents, MCP, testing, CLI, errors
Website docs The same guides, rendered
plugins/<id>/README.md Per plugin: configuration, routes, events, permissions, problems
pkg.go.dev Every exported identifier, with runnable examples
API.md What is stable: the host surface, the plugin SDK
docs/decisions.md Every design decision, with the reason

Stability

Polaris is pre-1.0. The host surface and the plugin SDK listed in API.md only change with a recorded decision and a release note, and CI checks every pull request for incompatible changes to them. Stored data (password hashes, encrypted secrets, issued tokens, the schema) stays readable across releases. CHANGELOG.md says what changes in each release; docs/v1.md what 1.0 still requires.

Contributing and security

Contributions go through pull requests with CI green; CONTRIBUTING.md has the workflow and AGENT.md the rules (tests first, make qa). Report a vulnerability privately through GitHub security advisories, not in an issue; SECURITY.md says what to include and what happens next.

License

MIT © 2026 2am.tech


Built and maintained by 2am.tech

Documentation

Overview

Package polaris is embedded authentication for Go services: sign-in (password, MFA, sessions), organizations and RBAC, and agent sign-in (API keys, an OAuth 2.1 / OIDC provider, agents, MCP) as plugins, self-hosted in the application's database.

An application touches this package only (plus plugin constructors, store/sqlstore and polaristest):

cfg, err := polaris.FromEnv(db, apikeys.New(apikeys.Config{})) // APP_KEY, AUTH_JWT_*, AUTH_ISSUER
p, err := polaris.New(cfg)                                     // fails at startup, naming the fix
_, err = p.Migrate(ctx)
mux.Handle("/", p.Handler())                                   // every Polaris route
mux.Handle("GET /api/invoices", p.Protect(h, "invoices.read")) // your routes
// in h: who, _ := polaris.PrincipalFrom(r.Context())

Keep your own user data in step with Config.Hooks (OnUserCreated / OnUserDeleted run in the account's transaction; Claims adds your claims to access tokens), join your transaction with sqlstore.WithTx, and drive accounts, organizations and sessions from Go with Users, Orgs, Sessions and Can. Errors match ErrNotFound, ErrConflict, ErrForbidden, ErrInvalidInput and ErrInvalidCredentials.

Plugin authors use the plugin SDK: packages wiring (Plugin, the read-only Graph), endpoint, manifest, event and token. API.md states what is stable in v0.x; llms.txt is the one-page integration guide.

Example

An app keeps a profile per account (OnUserCreated runs in the account's transaction), adds its own claim to access tokens, creates an account and a session from Go, and reads the principal on its own route.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	polaris "github.com/univeros/polaris.go"
	"github.com/univeros/polaris.go/config"
	"github.com/univeros/polaris.go/internal/contracttest"
	"github.com/univeros/polaris.go/schema"
	"github.com/univeros/polaris.go/store/memstore"
)

func main() {
	ctx := context.Background()
	private, public := contracttest.TestRSAKeyPEM() // use your AUTH_JWT_* keys (polaris.FromEnv)
	auth := config.Defaults()
	auth.Issuer = "https://auth.example.com"
	profiles := map[string]string{}
	p, err := polaris.New(polaris.Config{
		Secrets: config.Secrets{AppKey: "an-application-key-of-32-bytes!!", JWTPrivateKey: private, JWTPublicKey: public},
		Auth:    auth,
		DB:      memstore.New(schema.Core()...), // sqlstore.Open(ctx, store.Postgres, dsn) in production
		Hooks: polaris.Hooks{
			OnUserCreated: func(ctx context.Context, u polaris.User) error { profiles[u.ID] = "free"; return nil },
			Claims: func(ctx context.Context, in polaris.ClaimsInput) (map[string]any, error) {
				return map[string]any{"app_plan": profiles[in.UserID]}, nil
			},
		},
	})
	if err != nil {
		panic(err)
	}

	ada, err := p.Users().Create(ctx, polaris.NewUser{Email: "ada@example.com", EmailVerified: true})
	if err != nil {
		panic(err)
	}
	tokens, err := p.Sessions().Issue(ctx, polaris.SignIn{UserID: ada.ID})
	if err != nil {
		panic(err)
	}

	api := p.Protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		who, _ := polaris.PrincipalFrom(r.Context())
		fmt.Println(who.UserID == ada.ID, who.Kind, who.Claims["app_plan"])
	}))
	r := httptest.NewRequest(http.MethodGet, "/api/me", nil)
	r.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
	api.ServeHTTP(httptest.NewRecorder(), r)
}
Output:
true user free

Index

Examples

Constants

View Source
const (
	KindUser        = token.KindUser        // a Polaris session (sign-in) token
	KindAPIKey      = token.KindAPIKey      // an API key (plugins/apikeys)
	KindOAuthClient = token.KindOAuthClient // an OAuth access token (plugins/oauth)
	KindAgent       = token.KindAgent       // an agent's OAuth access token (plugins/agents)
)

The principal kinds.

Variables

View Source
var (
	// ErrNotFound: no such user, organization or membership.
	ErrNotFound = errors.New("polaris: not found")
	// ErrConflict: the email is taken, the slug is taken, the user is already a member, the last
	// owner would go, an erased account cannot be re-enabled.
	ErrConflict = errors.New("polaris: conflict")
	// ErrForbidden: the account is disabled, its email is unverified while verification is
	// required, or an authorization rule refuses.
	ErrForbidden = errors.New("polaris: forbidden")
	// ErrInvalidInput: a malformed email or name, an unknown role, a password failing the policy
	// (errors.As a *PasswordError for the rules it broke), an imported password hash the hasher
	// cannot verify (also security.ErrUnsupportedHash).
	ErrInvalidInput = errors.New("polaris: invalid input")
	// ErrInvalidCredentials: an unknown, expired or revoked refresh token.
	ErrInvalidCredentials = errors.New("polaris: invalid credentials")
)

Errors of the programmatic API (Users, Orgs, Sessions), matched with errors.Is. The error itself carries the reason; its message is safe to show a user.

Functions

func RequireKind added in v0.4.0

func RequireKind(kinds ...Kind) func(http.Handler) http.Handler

RequireKind returns middleware admitting only principals of one of kinds (KindUser to keep API keys, OAuth clients and agents off a route). Put it behind Protect, Require or Authenticate: a request without a principal is answered 401, one of another kind 403.

mux.Handle("POST /api/billing", p.Require()(polaris.RequireKind(polaris.KindUser)(billing)))

func RequireOrganization added in v0.4.0

func RequireOrganization(next http.Handler) http.Handler

RequireOrganization admits only principals acting in an organization (OrganizationID set). Put it behind Protect, Require or Authenticate: a request without a principal is answered 401, one without an active organization 403.

Types

type ClaimsInput

type ClaimsInput = wiring.ClaimsInput

ClaimsInput is the session an access token is minted for (Hooks.Claims).

type Config

type Config = wiring.Config

Config is everything a host decides; see wiring.Config. Secrets, Auth and DB are required; FromEnv fills them.

func FromEnv

func FromEnv(db store.Adapter, plugins ...Plugin) (Config, error)

FromEnv builds a Config from the process environment (APP_KEY, AUTH_JWT_PRIVATE_KEY, AUTH_JWT_PUBLIC_KEY, AUTH_ISSUER, … — see config.FromEnv) over db, with plugins. Every other port takes its default; set fields on the result to replace one.

cfg, err := polaris.FromEnv(db, apikeys.New(apikeys.Config{}))

type Hooks

type Hooks = wiring.Hooks

Hooks keep the host's own data in step with Polaris accounts and tokens; set Config.Hooks.

type ImportedUser added in v0.4.0

type ImportedUser struct {
	Email string
	// PasswordHash is the hash as the other system stored it. The default hasher verifies
	// Argon2id/Argon2i, bcrypt ($2a$, $2b$, $2y$), Django's pbkdf2_sha256$ and scrypt$, passlib's
	// $pbkdf2-sha256$, $pbkdf2-sha512$ and $scrypt$, and Firebase's scrypt written as
	// "$firebase-scrypt$ln=<mem_cost>,r=<rounds>,sep=<salt separator>,key=<signer key>$<salt>$<hash>"
	// (security.SupportedHashFormats). "" imports an account without a password.
	PasswordHash string
	DisplayName  string
	// EmailVerified imports the address as verified. Otherwise it stays unverified and no
	// verification email goes out (the user asks for one when sign-in requires it).
	EmailVerified bool
	// Disabled imports the account disabled; Enable re-enables it.
	Disabled bool
	// CreatedAt keeps the original creation time; zero is now. A time in the future is
	// ErrInvalidInput.
	CreatedAt time.Time
}

ImportedUser is an account brought from another system (your own users table, Auth0, Firebase, Django, Devise, Laravel, …) with the password hash that system stored, so the user keeps their password. Users().Import makes it.

type Kind

type Kind = token.Kind

Kind is the kind of credential a principal authenticated with.

type NewUser

type NewUser struct {
	Email       string
	Password    string // "" for an account that signs in another way (Sessions().Issue, passwordless, social)
	DisplayName string
	// EmailVerified creates the account verified; otherwise the verification email goes out, as
	// on registration.
	EmailVerified bool
}

NewUser is an account Users().Create makes.

type Organization

type Organization struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Slug      string    `json:"slug"`
	Status    string    `json:"status"` // "active" or "suspended"
	CreatedBy string    `json:"created_by"`
	CreatedAt time.Time `json:"created_at"`
}

Organization is a tenant as the host sees it.

type Orgs

type Orgs struct {
	// contains filtered or unexported fields
}

Orgs manages organizations and memberships in process, with the same rules (the last owner stays), events and audit as the HTTP routes. The caller is trusted: no actor authority is checked.

func (Orgs) AddMember

func (o Orgs) AddMember(ctx context.Context, organizationID, userID string, roles ...string) error

AddMember makes userID an active member holding roles (slugs of the organization's roles: "owner", "admin", "member" or its own), without an invitation. ErrConflict when the user already has a membership; ErrInvalidInput for an unknown role.

func (Orgs) Create

func (o Orgs) Create(ctx context.Context, ownerUserID, name, slug string) (Organization, error)

Create makes an organization owned by ownerUserID, with the owner, admin and member roles. slug "" derives one from name. A taken slug is ErrConflict; a bad name or slug ErrInvalidInput; an unknown owner ErrNotFound.

func (Orgs) Get

func (o Orgs) Get(ctx context.Context, organizationID string) (Organization, error)

Get returns the organization (ErrNotFound), suspended ones included.

func (Orgs) ListFor

func (o Orgs) ListFor(ctx context.Context, userID string) ([]Organization, error)

ListFor returns the active organizations userID is an active member of.

func (Orgs) RemoveMember

func (o Orgs) RemoveMember(ctx context.Context, organizationID, userID string) error

RemoveMember removes a member (ErrConflict for the last owner).

func (Orgs) SetRoles

func (o Orgs) SetRoles(ctx context.Context, organizationID, userID string, roles ...string) error

SetRoles replaces a member's roles (ErrConflict when it would demote the last owner).

type PasswordError

type PasswordError = identity.PasswordError

PasswordError lists the password-policy rules a password broke (Violations); it matches ErrInvalidInput.

type Plugin

type Plugin = wiring.Plugin

Plugin extends Polaris; see wiring.Plugin and its optional interfaces.

type Polaris

type Polaris struct {
	// contains filtered or unexported fields
}

Polaris is a running instance: the service graph and the HTTP pipeline over it. Safe for concurrent use.

func New

func New(cfg Config) (*Polaris, error)

New validates cfg, builds every service and the HTTP pipeline. Errors name what to fix.

p, err := polaris.New(polaris.Config{Secrets: secrets, Auth: auth, DB: db})
mux.Handle("/", p.Handler())

func (*Polaris) Authenticate added in v0.4.0

func (p *Polaris) Authenticate(next http.Handler) http.Handler

Authenticate identifies the caller when there is one, for a route open to everyone (a public page that personalises): a request with no credential reaches next anonymous (PrincipalFrom reports false), a request with a valid one reaches it with its principal. A credential that does not verify, is expired, revoked or denylisted is answered 401, as Protect answers it: a bad token is never downgraded to anonymous. An Authorization header with another scheme than Bearer or DPoP (a proxy's Basic credentials) is not a Polaris credential and passes anonymous.

It is middleware as it stands: r.Use(p.Authenticate) (chi), or p.Authenticate(next).

Example

A public page that greets a signed-in user: anonymous requests pass, a bad token does not.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	polaris "github.com/univeros/polaris.go"
	"github.com/univeros/polaris.go/config"
	"github.com/univeros/polaris.go/internal/contracttest"
	"github.com/univeros/polaris.go/schema"
	"github.com/univeros/polaris.go/store/memstore"
)

// signedIn is a Polaris instance and the access token of a user it signed in.
func signedIn() (*polaris.Polaris, string) {
	ctx := context.Background()
	private, public := contracttest.TestRSAKeyPEM()
	auth := config.Defaults()
	auth.Issuer = "https://auth.example.com"
	p, err := polaris.New(polaris.Config{
		Secrets: config.Secrets{AppKey: "an-application-key-of-32-bytes!!", JWTPrivateKey: private, JWTPublicKey: public},
		Auth:    auth,
		DB:      memstore.New(schema.Core()...),
	})
	if err != nil {
		panic(err)
	}
	ada, err := p.Users().Create(ctx, polaris.NewUser{Email: "ada@example.com", EmailVerified: true})
	if err != nil {
		panic(err)
	}
	tokens, err := p.Sessions().Issue(ctx, polaris.SignIn{UserID: ada.ID})
	if err != nil {
		panic(err)
	}
	return p, tokens.AccessToken
}

func get(h http.Handler, bearer string) int {
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	if bearer != "" {
		r.Header.Set("Authorization", "Bearer "+bearer)
	}
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	return w.Code
}

func main() {
	p, accessToken := signedIn()
	home := p.Authenticate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if who, ok := polaris.PrincipalFrom(r.Context()); ok {
			fmt.Println("welcome back,", who.Kind)
			return
		}
		fmt.Println("welcome, guest")
	}))
	fmt.Println(get(home, ""))
	fmt.Println(get(home, accessToken))
	fmt.Println(get(home, "forged"))
}
Output:
welcome, guest
200
welcome back, user
200
401

func (*Polaris) Can

func (p *Polaris) Can(ctx context.Context, principal Principal, permissions ...string) bool

Can reports whether principal holds every one of permissions in its active organization, re-resolved from the database now (roles, superadmin, a disabled user or a suspended membership apply at once; a delegated principal is limited to its credential's permissions). Use it for a check Protect cannot express, or for a principal outside a request (Principal{UserID: id, OrganizationID: org}). With no permissions, or when the database cannot answer (logged), it reports false.

func (*Polaris) Graph

func (p *Polaris) Graph() *wiring.Graph

Graph exposes every service read-only: the plugin SDK, for plugins, CLIs and advanced hosts. An application needs only the methods of Polaris.

func (*Polaris) Handler

func (p *Polaris) Handler() http.Handler

Handler serves every Polaris route (core and plugins) under Config.PathPrefix.

func (*Polaris) Migrate

func (p *Polaris) Migrate(ctx context.Context) ([]string, error)

Migrate creates every table core and the plugins need that the database lacks (never altering or dropping an existing one) and seeds the permission catalog and system roles. Idempotent: run it at every boot. It returns the tables it created.

func (*Polaris) Orgs

func (p *Polaris) Orgs() Orgs

Orgs returns the organization API.

func (*Polaris) Protect

func (p *Polaris) Protect(next http.Handler, permissions ...string) http.Handler

Protect guards a host handler with Polaris principals (session JWTs, and API keys, OAuth tokens or agent requests when those plugins are installed): 401 without one. With permissions, the caller's authority in the active organization must hold every one (403 otherwise); without, any authenticated principal passes and no authority is resolved until next calls PrincipalFrom (then once per request). next reads the complete principal with PrincipalFrom.

func (*Polaris) Prune

func (p *Polaris) Prune(ctx context.Context) (map[string]int64, error)

Prune deletes the expired transient rows Polaris accumulates (refresh tokens past their grace, used or expired verification, reset, OTP and invitation rows) and returns how many it deleted per table. Schedule it (a cron, a time.Ticker); it is idempotent and safe to run on every replica.

func (*Polaris) Require added in v0.4.0

func (p *Polaris) Require(permissions ...string) func(http.Handler) http.Handler

Require is Protect in the shape Go routers chain (chi's Use and With, a stdlib middleware chain): Require(permissions...)(next) is Protect(next, permissions...), with the same answers.

r.With(p.Require("invoices.read")).Get("/api/invoices", list) // chi
mux.Handle("GET /api/invoices", p.Require("invoices.read")(list))

Behind Authenticate, or another Require or Protect, that found a principal, it checks only the permissions: the credential is verified once per request.

Example

Require is Protect as middleware; RequireKind keeps API keys, OAuth clients and agents off a route meant for people.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	polaris "github.com/univeros/polaris.go"
	"github.com/univeros/polaris.go/config"
	"github.com/univeros/polaris.go/internal/contracttest"
	"github.com/univeros/polaris.go/schema"
	"github.com/univeros/polaris.go/store/memstore"
)

// signedIn is a Polaris instance and the access token of a user it signed in.
func signedIn() (*polaris.Polaris, string) {
	ctx := context.Background()
	private, public := contracttest.TestRSAKeyPEM()
	auth := config.Defaults()
	auth.Issuer = "https://auth.example.com"
	p, err := polaris.New(polaris.Config{
		Secrets: config.Secrets{AppKey: "an-application-key-of-32-bytes!!", JWTPrivateKey: private, JWTPublicKey: public},
		Auth:    auth,
		DB:      memstore.New(schema.Core()...),
	})
	if err != nil {
		panic(err)
	}
	ada, err := p.Users().Create(ctx, polaris.NewUser{Email: "ada@example.com", EmailVerified: true})
	if err != nil {
		panic(err)
	}
	tokens, err := p.Sessions().Issue(ctx, polaris.SignIn{UserID: ada.ID})
	if err != nil {
		panic(err)
	}
	return p, tokens.AccessToken
}

func get(h http.Handler, bearer string) int {
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	if bearer != "" {
		r.Header.Set("Authorization", "Bearer "+bearer)
	}
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	return w.Code
}

func main() {
	p, accessToken := signedIn()
	ok := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
	chain := func(h http.Handler, mw ...func(http.Handler) http.Handler) http.Handler {
		for i := len(mw) - 1; i >= 0; i-- {
			h = mw[i](h)
		}
		return h
	}
	fmt.Println(get(chain(ok, p.Require()), ""))
	fmt.Println(get(chain(ok, p.Require(), polaris.RequireKind(polaris.KindUser)), accessToken))
	fmt.Println(get(chain(ok, p.Require(), polaris.RequireOrganization), accessToken))
	fmt.Println(get(chain(ok, p.Require("members.update")), accessToken))
}
Output:
401
200
403
403

func (*Polaris) Sessions

func (p *Polaris) Sessions() Sessions

Sessions returns the session API.

func (*Polaris) Users

func (p *Polaris) Users() Users

Users returns the account API.

type Principal

type Principal struct {
	// UserID is the account acting: the user, the owner of an API key, the user an OAuth client
	// or agent acts for. "" for an OAuth client acting for itself (client credentials).
	UserID string `json:"user_id"`
	// OrganizationID is the active organization, "" when none.
	OrganizationID string `json:"organization_id"`
	// Roles and Permissions are the caller's effective authority in OrganizationID, resolved from
	// the database for this request (a delegated credential's permissions are already intersected
	// with what it may use). Never nil.
	Roles       []string `json:"roles"`
	Permissions []string `json:"permissions"`
	Kind        Kind     `json:"kind"`
	// Delegated is true for an API key, OAuth client or agent acting with a subset of its owner's
	// permissions; such a credential may not self-serve (create organizations, keys, factors).
	Delegated bool `json:"delegated"`
	// ClientID is the OAuth client (KindOAuthClient, KindAgent); AgentID the agent (KindAgent);
	// KeyID the API key (KindAPIKey). "" otherwise.
	ClientID string `json:"client_id,omitempty"`
	AgentID  string `json:"agent_id,omitempty"`
	KeyID    string `json:"key_id,omitempty"`
	// Claims are every claim of the credential, including the app's own (Hooks.Claims).
	Claims map[string]any `json:"claims,omitempty"`
	// contains filtered or unexported fields
}

Principal is who is calling: the authenticated user, API key, OAuth client or agent of a request that Protect (or a Polaris route) let through. Read it with PrincipalFrom. It is a plain value: keep it, log it, pass it to Can.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) (Principal, bool)

PrincipalFrom returns the principal of a request Protect or a Polaris route authenticated. ok is false on an unauthenticated request, and when the caller's authority cannot be resolved (the database failed; Polaris logs it): treat both as "no principal".

Behind Protect without permissions, the first call resolves the authority (one query) and the request keeps it; a handler that never calls PrincipalFrom costs no query. Behind Protect with permissions it was resolved already.

mux.Handle("GET /api/invoices", p.Protect(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	who, _ := polaris.PrincipalFrom(r.Context())
	list(w, who.UserID, who.OrganizationID)
}), "invoices.read"))

type Sessions

type Sessions struct {
	// contains filtered or unexported fields
}

Sessions opens, refreshes and ends sessions in process, with the same rules, events and audit as the HTTP routes.

func (Sessions) Issue

func (s Sessions) Issue(ctx context.Context, in SignIn) (Tokens, error)

Issue opens a session for a sign-in the host verified: the account checks of sign-in apply (a disabled account, or an unverified email when verification is required, is ErrForbidden) but not the password or the MFA gate. Access tokens carry Hooks.Claims.

func (Sessions) Refresh

func (s Sessions) Refresh(ctx context.Context, refreshToken string) (Tokens, error)

Refresh exchanges a refresh token for new tokens, rotating it. An unknown, expired, revoked or reused one is ErrInvalidCredentials (reuse also ends the whole session).

func (Sessions) Revoke

func (s Sessions) Revoke(ctx context.Context, sessionID string) error

Revoke ends one session (Tokens.SessionID; the sid claim). Ending an ended session is a no-op.

func (Sessions) RevokeAll

func (s Sessions) RevokeAll(ctx context.Context, userID string) error

RevokeAll ends every session of the user (logout everywhere).

type SignIn

type SignIn struct {
	UserID string
	// AMR says how the user authenticated, RFC 8176 values ("pwd", "otp", "hwk", …); empty is
	// ["custom"].
	AMR       []string
	IP        string // recorded on the session; optional
	UserAgent string // recorded on the session; optional
}

SignIn is a sign-in the host verified itself (its own SSO, a magic link of its own, a device it trusts).

type Tokens

type Tokens struct {
	AccessToken      string    `json:"access_token"`
	RefreshToken     string    `json:"refresh_token"`
	TokenType        string    `json:"token_type"` // "Bearer"
	ExpiresIn        int       `json:"expires_in"` // access-token lifetime, seconds
	RefreshExpiresAt time.Time `json:"refresh_expires_at"`
	SessionID        string    `json:"session_id"`
}

Tokens are a session's credentials, as the sign-in route answers them.

func (Tokens) GoString

func (t Tokens) GoString() string

GoString keeps both bearer secrets out of %#v output.

func (Tokens) LogValue

func (t Tokens) LogValue() slog.Value

LogValue keeps both bearer secrets out of logs.

func (Tokens) String

func (t Tokens) String() string

String keeps both bearer secrets out of fmt output.

type User

type User = wiring.User

User is an account as the host sees it: profile and state, never credentials.

type Users

type Users struct {
	// contains filtered or unexported fields
}

Users manages accounts in process, with the same rules, events and audit as the HTTP routes. The caller is trusted: no permission is checked (the actor recorded is "system").

func (Users) ByEmail

func (u Users) ByEmail(ctx context.Context, email string) (User, error)

ByEmail returns the account holding email, matched as sign-in matches it (ErrNotFound).

func (Users) Create

func (u Users) Create(ctx context.Context, in NewUser) (User, error)

Create makes an account, running Hooks.OnUserCreated in its transaction. A taken email is ErrConflict; a bad email, name or password ErrInvalidInput (*PasswordError lists the rules).

func (Users) Delete

func (u Users) Delete(ctx context.Context, userID string) error

Delete erases the account (right to erasure): the row stays as an anonymized tombstone so references hold, personal data and credentials go, every session ends, and Hooks.OnUserDeleted runs in the erasing transaction.

func (Users) Disable

func (u Users) Disable(ctx context.Context, userID string) error

Disable disables the account and ends every session; sign-in then refuses it. Disabling a disabled account is a no-op.

func (Users) Enable

func (u Users) Enable(ctx context.Context, userID string) error

Enable re-enables a disabled or locked account (ErrConflict for an erased one).

func (Users) Get

func (u Users) Get(ctx context.Context, userID string) (User, error)

Get returns the account userID (ErrNotFound).

func (Users) Import added in v0.4.0

func (u Users) Import(ctx context.Context, in ImportedUser) (User, error)

Import creates an account from another system, keeping its password hash: the user signs in with the password they already have, and that first sign-in replaces the hash with the configured Argon2id. Nothing is hashed or emailed, so a batch is fast; run it inside your transaction (sqlstore.WithTx) to import all or nothing. Hooks.OnUserCreated runs in the account's transaction and event user.registered is dispatched, as for Create.

A hash the configured hasher cannot verify (an unknown format, a malformed string, a cost out of bounds) is ErrInvalidInput, also matching security.ErrUnsupportedHash, with a message that lists the supported formats; a taken email is ErrConflict; a bad email or name ErrInvalidInput. A custom Config.Hasher must implement security.HashChecker.

Example

Users from another system keep their passwords: import each with the hash it stored (here a bcrypt hash; Django, passlib and Firebase hashes work the same way), and the first sign-in replaces it with Argon2id.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	polaris "github.com/univeros/polaris.go"
	"github.com/univeros/polaris.go/config"
	"github.com/univeros/polaris.go/internal/contracttest"
	"github.com/univeros/polaris.go/schema"
	"github.com/univeros/polaris.go/store/memstore"
)

func main() {
	ctx := context.Background()
	private, public := contracttest.TestRSAKeyPEM() // use your AUTH_JWT_* keys (polaris.FromEnv)
	auth := config.Defaults()
	auth.Issuer = "https://auth.example.com"
	p, err := polaris.New(polaris.Config{
		Secrets: config.Secrets{AppKey: "an-application-key-of-32-bytes!!", JWTPrivateKey: private, JWTPublicKey: public},
		Auth:    auth,
		DB:      memstore.New(schema.Core()...), // sqlstore.Open(ctx, store.Postgres, dsn) in production
	})
	if err != nil {
		panic(err)
	}

	// In a migration, loop over your rows inside one transaction: sqlstore.WithTx(ctx, tx).
	ada, err := p.Users().Import(ctx, polaris.ImportedUser{
		Email:         "ada@example.com",
		PasswordHash:  "$2y$04$9xkaXv9u52gB5CSHs990Rujqpwb54f2v3nd7nRc.mRPDPsGvyU1R6", // the password is "bcrypt"
		EmailVerified: true,
	})
	if err != nil {
		panic(err) // errors.Is(err, polaris.ErrInvalidInput): a hash the hasher cannot verify
	}

	login := httptest.NewRequest(http.MethodPost, "/auth/login",
		strings.NewReader(`{"email": "ada@example.com", "password": "bcrypt"}`))
	login.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	p.Handler().ServeHTTP(rec, login) // verifies the bcrypt hash, stores an Argon2id one
	fmt.Println(ada.Email, rec.Code)
}
Output:
ada@example.com 200

func (Users) SetPassword

func (u Users) SetPassword(ctx context.Context, userID, password string) error

SetPassword sets the account's password under the policy (ErrInvalidInput) and ends every session, as a password reset does.

Directories

Path Synopsis
Package agent is the Go agent SDK of Polaris: how a Go program signs in to a Polaris server as an AI agent (the plugins/agents protocol).
Package agent is the Go agent SDK of Polaris: how a Go program signs in to a Polaris server as an AI agent (the plugins/agents protocol).
Package authz is Polaris's role-based authorization: the code-defined permission catalog and its seeder, the resolver that turns a user and an active organization into an Authority (role slugs and permission keys), the Gate that checks it, the escalation guard and the session-principal resolver that puts roles into access tokens.
Package authz is Polaris's role-based authorization: the code-defined permission catalog and its seeder, the resolver that turns a user and an active organization into an Authority (role slugs and permission keys), the Gate that checks it, the escalation guard and the session-principal resolver that puts roles into access tokens.
Package cache is the short-lived key/value port Polaris uses for rate-limit counters, replay guards, flow state and the access-token denylist.
Package cache is the short-lived key/value port Polaris uses for rate-limit counters, replay guards, flow state and the access-token denylist.
Package cli is the polaris command line as a library: schema export, creation, diff and drop, migrations, the manifest, a doctor, key generation, `.env` scaffolding, the MCP stdio server and the plugins' maintenance commands (audit, admin, anonymous).
Package cli is the polaris command line as a library: schema export, creation, diff and drop, migrations, the manifest, a doctor, key generation, `.env` scaffolding, the MCP stdio server and the plugins' maintenance commands (audit, admin, anonymous).
Package clock is the time port.
Package clock is the time port.
cmd
polaris command
Command polaris is the standalone Polaris command line: the instance comes from the environment and .env, the database from DATABASE_URL or --dsn, the plugins from --plugins.
Command polaris is the standalone Polaris command line: the instance comes from the environment and .env, the database from DATABASE_URL or --dsn, the plugins from --plugins.
Package config holds Polaris configuration: the boot secrets (Secrets) and the auth settings (Auth), with their defaults, environment variables and validation rules.
Package config holds Polaris configuration: the boot secrets (Secrets) and the auth settings (Auth), with their defaults, environment variables and validation rules.
Package endpoint is the contract between the request pipeline and the code that serves one route: an Endpoint receives the request's Input and returns a Result.
Package endpoint is the contract between the request pipeline and the code that serves one route: an Endpoint receives the request's Input and returns a Result.
Package event is the domain-event port.
Package event is the domain-event port.
examples
agents command
Command agents is the agent story end to end in one process: a Polaris server that offers two capabilities to AI agents, and an agent, written with the Go agent SDK, that uses them.
Command agents is the agent story end to end in one process: a Polaris server that offers two capabilities to AI agents, and an agent, written with the Go agent SDK, that uses them.
api-keys command
Command api-keys adds user and organization API keys to Polaris: a key (`Authorization: Bearer pk_live_…` or `x-api-key`) authenticates every Polaris route and every host route behind Protect as its owner, limited to the key's permissions.
Command api-keys adds user and organization API keys to Polaris: a key (`Authorization: Bearer pk_live_…` or `x-api-key`) authenticates every Polaris route and every host route behind Protect as its owner, limited to the key's permissions.
b2b command
Command b2b is a multi-tenant SaaS on Polaris: every customer is an organization with its own members, roles and API keys; the host's own permissions (projects.read, projects.write) gate the host's own routes; invitations bring colleagues in; and an organization admin connects their company's identity provider (OIDC or SAML single sign-on) and directory (SCIM provisioning).
Command b2b is a multi-tenant SaaS on Polaris: every customer is an organization with its own members, roles and API keys; the host's own permissions (projects.read, projects.write) gate the host's own routes; invitations bring colleagues in; and an organization admin connects their company's identity provider (OIDC or SAML single sign-on) and directory (SCIM provisioning).
hooks command
Command hooks keeps the host's own data in step with Polaris: a `profiles` table of the app's, next to Polaris's tables in the same database.
Command hooks keeps the host's own data in step with Polaris: a `profiles` table of the app's, next to Polaris's tables in the same database.
mcp command
Command mcp protects an MCP server of the host's own with Polaris-issued tokens, and mounts Polaris's own MCP endpoint beside it.
Command mcp protects an MCP server of the host's own with Polaris-issued tokens, and mounts Polaris's own MCP endpoint beside it.
minimal command
Command minimal is the smallest complete Polaris host: core authentication (register, verify, login, refresh, MFA, organizations, RBAC) on SQLite, plus one host route protected by Polaris.
Command minimal is the smallest complete Polaris host: core authentication (register, verify, login, refresh, MFA, organizations, RBAC) on SQLite, plus one host route protected by Polaris.
signin-methods command
Command signin-methods is one Polaris server with every way to sign in besides a password: magic links and email codes (passwordless), usernames, guest sessions converted on sign-up (anonymous), several accounts per device (multisession), a generic OpenID Connect provider (social), passkeys, plus the messaging plugin delivering the mails and sentinel scoring every attempt in observe mode.
Command signin-methods is one Polaris server with every way to sign in besides a password: magic links and email codes (passwordless), usernames, guest sessions converted on sign-up (anonymous), several accounts per device (multisession), a generic OpenID Connect provider (social), passkeys, plus the messaging plugin delivering the mails and sentinel scoring every attempt in observe mode.
webapp command
Command webapp is a complete server-rendered app on Polaris: the sign-in, sign-up, email verification, password reset and sign-out pages of plugins/ui, and a /dashboard only a signed-in browser sees.
Command webapp is a complete server-rendered app on Polaris: the sign-in, sign-up, email verification, password reset and sign-out pages of plugins/ui, and a /dashboard only a signed-in browser sees.
Package identity runs the account flows: registration and email verification, password login with windowed lockout and the MFA hand-off, password forgot/reset/change, and user administration (read, update, disable, enable, erase).
Package identity runs the account flows: registration and email verification, password login with windowed lockout and the MFA hand-off, password forgot/reset/change, and user administration (read, update, disable, enable, erase).
internal
apispec
Package apispec embeds the route specs every Polaris endpoint is built from: api/<package>/**/*.yaml (method, path, input rules, output, errors, events) and api/core/schema.json.
Package apispec embeds the route specs every Polaris endpoint is built from: api/<package>/**/*.yaml (method, path, input rules, output, errors, events) and api/core/schema.json.
contracttest
Package contracttest replays the recorded contract fixtures against a Go http.Handler.
Package contracttest replays the recorded contract fixtures against a Go http.Handler.
httpapi
Package httpapi holds core's endpoints: one endpoint.Endpoint per route in internal/apispec/api/core, registered by route name.
Package httpapi holds core's endpoints: one endpoint.Endpoint per route in internal/apispec/api/core, registered by route name.
jwtverify
Package jwtverify checks Polaris access tokens the way a resource server does (RFC 9068 §4), without the issuer's database: the signature by kid against local keys or a remote JWK Set, the typ, iss, aud, exp and nbf.
Package jwtverify checks Polaris access tokens the way a resource server does (RFC 9068 §4), without the issuer's database: the signature by kid against local keys or a remote JWK Set, the typ, iss, aud, exp and nbf.
maintenance
Package maintenance holds the housekeeping jobs a host schedules (a cron, a ticker).
Package maintenance holds the housekeeping jobs a host schedules (a cron, a ticker).
netguard
Package netguard is the outbound-request guard plugins use when a URL comes from a tenant or a client (OIDC issuers, client metadata documents, jwks_uri, domain-verification files): connect only to public unicast addresses, decided after DNS resolution, so a public name that resolves to an internal address (cloud metadata, internal services) is refused too.
Package netguard is the outbound-request guard plugins use when a URL comes from a tenant or a client (OIDC issuers, client metadata documents, jwks_uri, domain-verification files): connect only to public unicast addresses, decided after DNS resolution, so a public name that resolves to an internal address (cloud metadata, internal services) is refused too.
observe
Package observe has the observability listeners of the core events (docs/auth/events.md): the audit trail written to auth_audit_log and the event counter.
Package observe has the observability listeners of the core events (docs/auth/events.md): the audit trail written to auth_audit_log and the event counter.
services
Package services hands core (package polaris, internal/httpapi, polaristest, cli) the concrete services of a wiring.Graph.
Package services hands core (package polaris, internal/httpapi, polaristest, cli) the concrete services of a wiring.Graph.
version
Package version reports which release of Polaris is running, from the build information the Go toolchain records: the version of github.com/univeros/polaris.go a host's go.mod requires, or of this module when it is the one being built.
Package version reports which release of Polaris is running, from the build information the Go toolchain records: the version of github.com/univeros/polaris.go a host's go.mod requires, or of this module when it is the one being built.
Package manifest loads the endpoint specs (api/**/*.yaml) that declare every Polaris route, checks request input against their field rules, and exports them: the JSON manifest and an OpenAPI 3.1 document.
Package manifest loads the endpoint specs (api/**/*.yaml) that declare every Polaris route, checks request input against their field rules, and exports them: the JSON manifest and an OpenAPI 3.1 document.
Package metrics is where Polaris counts its domain events.
Package metrics is where Polaris counts its domain events.
Package mfa holds multi-factor authentication.
Package mfa holds multi-factor authentication.
Package model holds core's records as plain Go values, one struct per table of schema.Core().
Package model holds core's records as plain Go values, one struct per table of schema.Core().
Package notify delivers one-time codes and account notifications by email and SMS.
Package notify delivers one-time codes and account notifications by email and SMS.
notifytest
Package notifytest has recording notify drivers for tests: they keep what they were asked to send so a test can assert the recipient and read the one-time code.
Package notifytest has recording notify drivers for tests: they keep what they were asked to send so a test can assert the recipient and read the one-time code.
Package orgs manages organizations, their members, invitations and roles, enforcing the multi-tenant invariants a permission check alone cannot express:
Package orgs manages organizations, their members, invitations and roles, enforcing the multi-tenant invariants a permission check alone cannot express:
Package pipeline is the HTTP face of Polaris: it routes requests by the endpoint manifest and runs them through a fixed middleware order (part of the contract: each step sees what the earlier ones set, and refuses before the later ones run) to the registered endpoint:
Package pipeline is the HTTP face of Polaris: it routes requests by the endpoint manifest and runs them through a fixed middleware order (part of the contract: each step sees what the earlier ones set, and refuses before the later ones run) to the registered endpoint:
plugins
admin
Package admin is the admin plugin: the operator API under /admin over users, sessions, MFA, organizations, audit drains and statistics, for admin users and operator API keys, every action recorded in the audit trail as admin.<action>.
Package admin is the admin plugin: the operator API under /admin over users, sessions, MFA, organizations, audit drains and statistics, for admin users and operator API keys, every action recorded in the audit trail as admin.<action>.
agents
Package agents makes AI agents Polaris principals (plugin id "agents"): agents registered by their owners or enrolled by hosts, each an OAuth client of the oauth plugin (client credentials for an autonomous agent, token exchange with act for a delegated one; private_key_jwt, a pcs_ secret or the user's token), signed request JWTs (typ agent+jwt: aud the exact URL, jti once, exp - iat at most 5 min, htm/htu/body_hash binding), capability grants with constraints and budgets approved by a person (device code, CIBA push, in-app) with the strength the risk needs or by policy, one execution path with a signed receipt hash chain, and a kill switch.
Package agents makes AI agents Polaris principals (plugin id "agents"): agents registered by their owners or enrolled by hosts, each an OAuth client of the oauth plugin (client credentials for an autonomous agent, token exchange with act for a delegated one; private_key_jwt, a pcs_ secret or the user's token), signed request JWTs (typ agent+jwt: aud the exact URL, jti once, exp - iat at most 5 min, htm/htu/body_hash binding), capability grants with constraints and budgets approved by a person (device code, CIBA push, in-app) with the strength the risk needs or by policy, one execution path with a signed receipt hash chain, and a kill switch.
anonymous
Package anonymous is the guest-session plugin: a visitor gets a session before having an account, and once they sign up or in by any method the guest is converted into that account through a host hook that moves what the host kept under the guest's id.
Package anonymous is the guest-session plugin: a visitor gets a session before having an account, and once they sign up or in by any method the guest is converted into that account through a host hook that moves what the host kept under the guest's id.
apikeys
Package apikeys is the API-keys plugin: keys owned by users and by organizations (pk_live_…, pk_test_…), each with a subset of its owner's permissions, an optional rate limit of its own, an expiry, rotation with a grace window and revocation.
Package apikeys is the API-keys plugin: keys owned by users and by organizations (pk_live_…, pk_test_…), each with a subset of its owner's permissions, an optional rate limit of its own, an expiry, rotation with a grace window and revocation.
audit
Package audit is the audit plugin: every Polaris event becomes a catalogued, redacted, append-only record in polaris_audit_event that callers query per user (GET /audit/me) and per organization (GET /audit/organization/{id}, audit.read), streamed to extra sinks and to each organization's drains, pruned by a retention policy and, optionally, chained by SHA-256 for tamper evidence.
Package audit is the audit plugin: every Polaris event becomes a catalogued, redacted, append-only record in polaris_audit_event that callers query per user (GET /audit/me) and per organization (GET /audit/organization/{id}, audit.read), streamed to extra sinks and to each organization's drains, pruned by a retention policy and, optionally, chained by SHA-256 for tamper evidence.
mcp
Package mcp is Polaris and the Model Context Protocol, two halves sharing token verification.
Package mcp is Polaris and the Model Context Protocol, two halves sharing token verification.
messaging
Package messaging is the messaging plugin: core's verification, reset, invitation, one-time-code and security messages rendered from templates you can override per instance and per organization, translated (en, es, de, fr, pt bundled), capped per recipient, and sent through the channels you choose (SMTP, Twilio, Vonage, any HTTP SMS API, a log, memory in tests).
Package messaging is the messaging plugin: core's verification, reset, invitation, one-time-code and security messages rendered from templates you can override per instance and per organization, translated (en, es, de, fr, pt bundled), capped per recipient, and sent through the channels you choose (SMTP, Twilio, Vonage, any HTTP SMS API, a log, memory in tests).
multisession
Package multisession is the multi-session plugin: several accounts signed in on one device (one browser), a switch between them without signing in again, signing one out, and the device's last sign-in method for the client to pre-select its button.
Package multisession is the multi-session plugin: several accounts signed in on one device (one browser), a switch between them without signing in again, signing one out, and the device's last sign-in method for the client to pre-select its button.
oauth
Package oauth makes Polaris an OAuth 2.1 and OpenID Connect provider (plugin id "oauth"): authorization code with PKCE (S256 only) and consent, rotating refresh tokens, client credentials, the device flow (RFC 8628), backchannel authentication (OpenID CIBA, poll mode), token exchange (RFC 8693, with act), DPoP (RFC 9449), dynamic registration (RFC 7591, off by default), client ID metadata documents (an https client_id fetched, validated and cached), introspection, revocation, userinfo and the discovery documents.
Package oauth makes Polaris an OAuth 2.1 and OpenID Connect provider (plugin id "oauth"): authorization code with PKCE (S256 only) and consent, rotating refresh tokens, client credentials, the device flow (RFC 8628), backchannel authentication (OpenID CIBA, poll mode), token exchange (RFC 8693, with act), DPoP (RFC 9449), dynamic registration (RFC 7591, off by default), client ID metadata documents (an https client_id fetched, validated and cached), introspection, revocation, userinfo and the discovery documents.
passkey
Package passkey is the passkey plugin: WebAuthn registration from a session, discoverable sign-in with conditional UI (the browser offers the user's passkeys, autofill included) ending in core's login envelope with amr ["passkey"], naming and removal; and, by default, every passkey is also a core MFA factor of type "passkey", verified through core's own /auth/mfa/verify and /auth/mfa/step-up with the assertion JSON as the code.
Package passkey is the passkey plugin: WebAuthn registration from a session, discoverable sign-in with conditional UI (the browser offers the user's passkeys, autofill included) ending in core's login envelope with amr ["passkey"], naming and removal; and, by default, every passkey is also a core MFA factor of type "passkey", verified through core's own /auth/mfa/verify and /auth/mfa/step-up with the assertion JSON as the code.
passwordless
Package passwordless is the passwordless plugin: four ways to sign in without a password, each ending in core's login envelope behind core's MFA gate.
Package passwordless is the passwordless plugin: four ways to sign in without a password, each ending in core's login envelope behind core's MFA gate.
scim
Package scim is the SCIM plugin: a SCIM 2.0 server (RFC 7643, 7644) per organization.
Package scim is the SCIM plugin: a SCIM 2.0 server (RFC 7643, 7644) per organization.
sentinel
Package sentinel is the sentinel plugin: a local risk engine in front of sign-up, sign-in, password reset and code sends.
Package sentinel is the sentinel plugin: a local risk engine in front of sign-up, sign-in, password reset and code sends.
social
Package social is the social sign-in plugin: OAuth 2.0 and OpenID Connect sign-in and sign-up through Google, Apple, Microsoft, GitHub and fifteen more providers, or any other OAuth 2 server; account linking under a policy; Google One Tap; provider tokens on the user's behalf (stored encrypted, refreshed when expiring); and an OAuth proxy so preview and local origins sign in through the stable origin registered at the providers.
Package social is the social sign-in plugin: OAuth 2.0 and OpenID Connect sign-in and sign-up through Google, Apple, Microsoft, GitHub and fifteen more providers, or any other OAuth 2 server; account linking under a policy; Google One Tap; provider tokens on the user's behalf (stored encrypted, refreshed when expiring); and an OAuth proxy so preview and local origins sign in through the stable origin registered at the providers.
sso
Package sso is the SSO plugin: per-organization SAML 2.0 and OpenID Connect identity providers, verified domains that route an email to its organization's provider, just-in-time users and memberships, single logout in both directions, the organization's own self-service routes and the operators' view.
Package sso is the SSO plugin: per-organization SAML 2.0 and OpenID Connect identity providers, verified domains that route an email to its organization's provider, just-in-time users and memberships, single logout in both directions, the organization's own self-service routes and the operators' view.
ui
Package ui is the pages plugin: server-rendered sign-in, two-step verification, sign-up, email verification, forgot and reset password, sign-out and, with plugins/oauth, the OAuth consent and device pages.
Package ui is the pages plugin: server-rendered sign-in, two-step verification, sign-up, email verification, forgot and reset password, sign-out and, with plugins/oauth, the OAuth consent and device pages.
username
Package username is the username plugin: a user sets a username (PATCH /username) and signs in with it or with the email (POST /username/sign-in) through core's password path, so lockout, timing parity, the email-verification rule, the MFA gate and the login envelope are core's.
Package username is the username plugin: a user sets a username (PATCH /username) and signs in with it or with the email (POST /username/sign-in) through core's password path, so lockout, timing parity, the email-verification rule, the MFA gate and the login envelope are core's.
Package polaristest boots a complete Polaris server for tests: a fresh database (SQLite in a temp file by default; see WithDialect and EnvDB) with the schema and permission catalog installed, test RSA keys, recording mailer, SMS sender and event log, and a frozen rate-limit clock — the environment the contract fixtures replay in.
Package polaristest boots a complete Polaris server for tests: a fresh database (SQLite in a temp file by default; see WithDialect and EnvDB) with the schema and permission catalog installed, test RSA keys, recording mailer, SMS sender and event log, and a frozen rate-limit clock — the environment the contract fixtures replay in.
Package ratelimit counts requests in fixed windows and computes the rate-limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset and, when refused, Retry-After).
Package ratelimit counts requests in fixed windows and computes the rate-limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset and, when refused, Retry-After).
Package repository reads and writes core's records (package model) through a store.Adapter, one typed repository per table with explicit row mapping.
Package repository reads and writes core's records (package model) through a store.Adapter, one typed repository per table with explicit row mapping.
Package schema is the database schema as data.
Package schema is the database schema as data.
Package security holds Polaris's secret-handling primitives: password hashing (Argon2id, PHC strings), keyed hashing of verifiable secrets (Pepper), authenticated encryption of secrets at rest (XChaCha20-Poly1305) and breached-password screening (HIBP k-anonymity).
Package security holds Polaris's secret-handling primitives: password hashing (Argon2id, PHC strings), keyed hashing of verifiable secrets (Pepper), authenticated encryption of secrets at rest (XChaCha20-Poly1305) and breached-password screening (HIBP k-anonymity).
Package session runs the refresh-token session lifecycle: issuing a short-lived access JWT plus a rotating, opaque refresh token; refreshing with reuse detection; step-up and organization switches that re-mint without rotating; listing and revoking sessions.
Package session runs the refresh-token session lifecycle: issuing a short-lived access JWT plus a rotating, opaque refresh token; refreshing with reuse detection; step-up and organization switches that re-mint without rotating; listing and revoking sessions.
Package store is the persistence port: a row-level adapter over any database.
Package store is the persistence port: a row-level adapter over any database.
memstore
Package memstore is an in-memory store.Adapter for tests and prototypes.
Package memstore is an in-memory store.Adapter for tests and prototypes.
sqlstore
Package sqlstore is the store.Adapter over database/sql for PostgreSQL (pgx), MySQL and SQLite (modernc, no cgo): prepared statements only, nested transactions as savepoints, unique-constraint violations as store.ErrDuplicate.
Package sqlstore is the store.Adapter over database/sql for PostgreSQL (pgx), MySQL and SQLite (modernc, no cgo): prepared statements only, nested transactions as savepoints, unique-constraint violations as store.ErrDuplicate.
storetest
Package storetest is the store.Adapter conformance suite: every criteria form, ordering, paging, Increment, transactions with savepoints, duplicate keys and concurrent use, over core's tables.
Package storetest is the store.Adapter conformance suite: every criteria form, ordering, paging, Increment, transactions with savepoints, duplicate keys and concurrent use, over core's tables.
telemetry
otel
Package otel instruments Polaris with OpenTelemetry: a span and a duration measurement per HTTP request (Middleware), a span per database call (Store) and a counter of authentication outcomes (Listener).
Package otel instruments Polaris with OpenTelemetry: a span and a duration measurement per HTTP request (Middleware), a span per database call (Store) and a counter of authentication outcomes (Listener).
Package token mints and verifies Polaris access tokens: asymmetric JWTs (RS256 or EdDSA) with a kid header, managed iss/aud/iat/nbf/exp claims and the Polaris claim set, plus the JWK Set that publishes the verification keys.
Package token mints and verifies Polaris access tokens: asymmetric JWTs (RS256 or EdDSA) with a kid header, managed iss/aud/iat/nbf/exp claims and the Polaris claim set, plus the JWK Set that publishes the verification keys.
Package verify checks Polaris access tokens in a Go service that is not the Polaris host: a microservice with no access to the auth database.
Package verify checks Polaris access tokens in a Go service that is not the Polaris host: a microservice with no access to the auth database.
Package wiring builds every Polaris service from a Config, explicitly and once, without a container.
Package wiring builds every Polaris service from a Config, explicitly and once, without a container.

Jump to

Keyboard shortcuts

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