nine

package module
v0.2.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: 35 Imported by: 1 module, 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

9in Go SDK

9in

Official Go SDK for 9in: hosted login, OpenID Connect provider and SSO.

github.com/9in-io/go-sdk (package nine) uses only the standard library. Every call takes a context.Context, every type is safe for concurrent use, and it works with any router that speaks http.Handler.

  • Sign users in to web apps with nine.WebApp: /nine/login, /nine/callback and /nine/logout handlers, an encrypted cookie session (AES-256-GCM), refresh token rotation and RequireUser middleware. nine.WebAppAuth is the flow underneath: authorization code with PKCE, state, nonce, the RFC 9207 issuer check and ID token verification.
  • Protect your API: verify access tokens locally with every algorithm of the 9in key library, or in hybrid mode so revocations take effect at once. nine.RequireAuth is the net/http middleware.
  • Manage users through the Management API: users, sessions, single-use sign-in links and bulk import.
  • Keep users in your own database with the adapter protocol v2 (/authenticate, /user, /event) and signed requests and responses.
  • Receive webhooks, verify their signature and process each event once.
  • Sign in from CLIs and devices with the device flow (RFC 8628), and get tokens for your services with client credentials.

Requires Go 1.23 or later.

go get github.com/9in-io/go-sdk
import nine "github.com/9in-io/go-sdk"

Guides are at 9in.io/docs, and every function is documented on pkg.go.dev. The other 9in SDKs: JavaScript, Node.js, Next.js, PHP, Laravel.

Sign users in (web apps)

Create a Regular Web App in the console, with https://app.acme.com/nine/callback as a callback URL and https://app.acme.com/ as a logout URL, and set:

NINE_ISSUER=https://acme.9in.io      # or your custom login domain
NINE_CLIENT_ID=app_...
NINE_CLIENT_SECRET=...
NINE_SECRET=...                       # 32+ characters: openssl rand -base64 32 (encrypts the session cookie)
NINE_BASE_URL=https://app.acme.com    # http://localhost:3000 in development
# NINE_AUDIENCE=https://api.acme.com  # access tokens for your own API
package main

import (
	"fmt"
	"log"
	"net/http"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	app, err := nine.NewWebApp(nine.WebAppConfigFromEnv())
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	mux.Handle("/nine/", app) // /nine/login, /nine/signup, /nine/callback, /nine/logout
	mux.Handle("/dashboard", app.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user := nine.UserFrom(r.Context()) // Subject, Email, Name, … and every claim in Claims
		fmt.Fprintf(w, "Hello %s", user.Name)
	})))
	log.Fatal(http.ListenAndServe(":3000", mux))
}

Link to /nine/login (add ?return_to=/dashboard, screen=signup, login_hint=… or locale=de), /nine/signup and /nine/logout. Signed-out visitors of a RequireUser page are sent to the sign-in page and brought back; requests that aren't page navigations get a 401 JSON answer. app.Middleware loads the user without requiring one.

Call your API with the user's access token. It is refreshed shortly before it expires, and 9in rotates refresh tokens, so the new one is saved in the cookie: call AccessToken before you write the response body.

token, err := app.AccessToken(w, r) // nine.ErrLoginRequired when the session has ended

The session lives in the encrypted cookie (no server-side storage); NINE_SECRET can hold several comma-separated secrets while you rotate (the first encrypts). The WebAppConfig fields change the routes (BasePath), scopes, cookie name, session length, where users land (AfterSignInPath, AfterSignOutPath) and the error page (OnError).

Other routers

WebApp and every middleware are plain http.Handlers:

// chi
router := chi.NewRouter()
router.Mount("/nine", app)
router.With(app.RequireUser).Get("/dashboard", dashboard)

// gin
g := gin.Default()
g.Any("/nine/*action", gin.WrapH(app))
g.GET("/dashboard", gin.WrapH(app.RequireUser(http.HandlerFunc(dashboard))))

// echo
e := echo.New()
e.Any("/nine/*", echo.WrapHandler(app))
e.GET("/dashboard", echo.WrapHandler(app.RequireUser(http.HandlerFunc(dashboard))))
Your own session: WebAppAuth

WebAppAuth is the protocol without the cookie handling, for apps that keep sessions elsewhere (a database, gorilla/sessions, scs):

auth, err := nine.NewWebAppAuth(nine.WebAppAuthConfig{
	Issuer:       "https://acme.9in.io",
	ClientID:     os.Getenv("NINE_CLIENT_ID"),
	ClientSecret: os.Getenv("NINE_CLIENT_SECRET"), // leave empty for a public application
	RedirectURI:  "https://app.acme.com/nine/callback",
})

// /nine/login: keep login.Pending in the session (it holds the PKCE verifier), then redirect.
login, err := auth.CreateLogin(ctx, nine.LoginOptions{ReturnTo: "/dashboard"}) // Screen: "signup"
http.Redirect(w, r, login.URL, http.StatusFound)

// /nine/callback: checks state (once), iss and PKCE, and verifies the ID token.
tokens, err := auth.HandleCallback(ctx, r.URL.Query(), pending)
// tokens.Claims: sub, email, name, amr…; tokens.ReturnTo: a same-site path only

tokens, err = auth.EnsureFresh(ctx, tokens, time.Minute) // refreshed when needed: save the result
logoutURL, err := auth.LogoutURL(ctx, nine.LogoutOptions{IDTokenHint: tokens.IDToken, PostLogoutRedirectURI: "https://app.acme.com/"})

TokenSet and PendingLogin marshal to JSON. auth.Revoke, auth.UserInfo and auth.ClientCredentials cover the other endpoints.

Protect your API

verifier, err := nine.NewVerifier(nine.VerifierConfig{
	Issuer:   "https://acme.9in.io",
	Audience: "https://api.acme.com",
})

mux.Handle("GET /api/orders", nine.RequireAuth(verifier, "orders:read")(http.HandlerFunc(
	func(w http.ResponseWriter, r *http.Request) {
		claims := nine.ClaimsFrom(r.Context())
		fmt.Fprintf(w, "orders of %s", claims.Subject())
	})))

RequireAuth answers 401 invalid_token or 403 insufficient_scope with a WWW-Authenticate header, and 503 when tokens can't be checked (9in unreachable). verifier.Verify(ctx, token, scopes...) does the same check anywhere else.

Tokens are verified locally against your tenant's JWKS (cached for ten minutes, fetched again once when a token names an unknown key, with unknown keys throttled). Every algorithm of the 9in key library is supported: RS256/384/512, PS256/384/512, ES256, ES384 and EdDSA through JWKS, and HS256/384/512 when your API uses a shared secret (Secret: os.Getenv("NINE_API_SECRET")). The key's own algorithm is enforced, only access tokens (typ: at+jwt) are accepted, and the issuer, expiry, audience and scopes are checked.

Revocation: hybrid verification

A local check can't see revocations: a token revoked through /oauth/revoke, a sign-out or a blocked user keeps passing until it expires. With the credentials of a confidential application the verifier runs in hybrid mode: a local check, then one introspection per token, cached until a webhook says otherwise.

verifier, err := nine.NewVerifier(nine.VerifierConfig{
	Issuer:       "https://acme.9in.io",
	Audience:     "https://api.acme.com",
	ClientID:     os.Getenv("NINE_CLIENT_ID"),
	ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
	CacheTTL:     5 * time.Minute, // the longest an answer is trusted without news from 9in
})

// Subscribe this endpoint to token.revoked, session.revoked and the user.* events.
mux.Handle("POST /nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
	Secret:   os.Getenv("NINE_WEBHOOK_SECRET"),
	Verifier: verifier, // revocations evict cached answers
}))
Mode What it does
nine.ModeLocal Signature and claims only. No calls to 9in. The default without client credentials.
nine.ModeHybrid Local check, then one introspection per token. The answer is cached until a webhook says otherwise or CacheTTL passes; a refusal is cached until the token expires. The default with client credentials.
nine.ModeIntrospect Introspection on every call.

Opaque access tokens (9in_at_…) are always introspected, and cached in hybrid mode.

Several processes: a shared Store

By default each process keeps its answers in memory, so a revocation webhook only reaches the process that receives it; the others trust their cached answer for up to CacheTTL. Give every process the same nine.Store and the webhook reaches them all: the process that gets it writes a small revocation marker (for the token's jti, the session's sid or the user), and every process checks the markers before trusting a cached answer.

store := RedisStore{rdb} // any nine.Store: four methods, see below

verifier, err := nine.NewVerifier(nine.VerifierConfig{
	Issuer: "https://acme.9in.io", Audience: "https://api.acme.com",
	ClientID: os.Getenv("NINE_CLIENT_ID"), ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
	Store: store,
})
mux.Handle("POST /nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
	Secret: os.Getenv("NINE_WEBHOOK_SECRET"), Verifier: verifier,
	Store: store, // the same store also makes each event run once across processes
}))

A nine.Store is a key-value store with expiry: Get, Set, Delete, and an atomic Add (store only if the key is missing). With go-redis:

type RedisStore struct{ rdb *redis.Client }

func (s RedisStore) Get(ctx context.Context, key string) (string, bool, error) {
	v, err := s.rdb.Get(ctx, key).Result()
	if errors.Is(err, redis.Nil) {
		return "", false, nil
	}
	return v, err == nil, err
}

func (s RedisStore) Set(ctx context.Context, key, value string, ttl time.Duration) error {
	return s.rdb.Set(ctx, key, value, ttl).Err()
}

func (s RedisStore) Add(ctx context.Context, key, value string, ttl time.Duration) (bool, error) {
	return s.rdb.SetNX(ctx, key, value, ttl).Result()
}

func (s RedisStore) Delete(ctx context.Context, key string) error {
	return s.rdb.Del(ctx, key).Err()
}

// Optional (nine.MultiGetter): read an answer's markers in one round trip.
func (s RedisStore) GetMany(ctx context.Context, keys []string) ([]string, []bool, error) {
	vals, err := s.rdb.MGet(ctx, keys...).Result()
	if err != nil {
		return nil, nil, err
	}
	out, ok := make([]string, len(vals)), make([]bool, len(vals))
	for i, v := range vals {
		out[i], ok[i] = v.(string)
	}
	return out, ok, nil
}

Use a store that keeps keys until they expire (for Redis, a noeviction or volatile-* policy): a store that drops keys early under memory pressure can let a webhook run twice. When the store can't be read, the verifier asks 9in instead of trusting a cached answer; when a revocation can't be written, WebhookHandler answers 500 so 9in delivers the event again.

Manage users

Give a confidential application management scopes (Applications → app → API Access → Management API):

m, err := nine.NewManagementClient(nine.ManagementConfig{
	Issuer:       "https://acme.9in.io", // https://acme-sandbox.9in.io for the sandbox's users
	ClientID:     os.Getenv("NINE_CLIENT_ID"),
	ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
})

user, err := m.CreateUser(ctx, nine.NewUser{Email: "jane@acme.com", Password: "…", EmailVerified: true})
user, err = m.UpdateUser(ctx, user.ID, nine.UserChanges{"phone_number": "+447700900000", "phone_number_verified": true})
user, err = m.BlockUser(ctx, user.ID)
user, err = m.FindUser(ctx, "phone_number", "+447700900000") // or "email", "username"; nine.ErrNotFound when unknown

// Sessions: list them, end one (its sid), or sign the user out everywhere
sessions, err := m.ListUserSessions(ctx, user.ID)
err = m.RevokeSession(ctx, sessions[0].SID)
n, err := m.RevokeUserSessions(ctx, user.ID)

// A single-use sign-in link (magic links, moving a signed-in user from your app to 9in)
link, err := m.CreateLoginLink(ctx, user.ID, nine.LoginLinkOptions{ReturnTo: "https://app.acme.com/nine/callback", TTL: 10 * time.Minute})

// Bulk import (500 per call): old ids, password hashes (bcrypt, argon2, PBKDF2, Firebase scrypt), social identities
results, err := m.ImportUsers(ctx, []nine.ImportUser{
	{ID: "auth0|42", NewUser: nine.NewUser{Email: "jane@acme.com", PasswordHash: "$2b$10$…"}},
}, nine.ImportOptions{OnConflict: "skip", Source: "auth0"})

The client gets and caches a client-credentials token for each management scope it uses. Users and sessions have the API's snake_case JSON names (email_verified, phone_number, created_at), and UserChanges takes them as keys. Errors are *nine.Error with the API's code (identifier_taken, invalid_user, not_found…), HTTP status and Details.

Keep users in your own database

Point a user database connection at your server and implement three methods:

type users struct{ db *sql.DB }

func (u users) Authenticate(ctx context.Context, id nine.Identifier, password string) (*nine.AdapterUser, error) {
	user, err := findByLogin(ctx, u.db, id.Type, id.Value) // id.Type: "email", "username" or "phone"
	if err != nil || user == nil || !checkPassword(user, password) {
		return nil, nine.ErrInvalidCredentials
	}
	if user.Disabled {
		return nil, nine.ErrUserBlocked
	}
	return &nine.AdapterUser{ID: user.ID, Email: user.Email, EmailVerified: true, Name: user.Name}, nil
}

func (u users) FindUser(ctx context.Context, q nine.UserQuery) (*nine.AdapterUser, error) {
	user, err := findByQuery(ctx, u.db, q) // q.ID (your id) or q.Identifier
	if err != nil || user == nil {
		return nil, err // nil, nil: there is no such user (404)
	}
	return &nine.AdapterUser{ID: user.ID, Email: user.Email, Name: user.Name}, nil
}

func (u users) OnEvent(ctx context.Context, e *nine.AdapterEvent) error {
	// e.EventType "otp.requested": deliver e.Data["code"] to e.Data["to"] (e.Data["channel"] is "email" or "sms")
	return nil
}

// Serves /nine/authenticate, /nine/user and /nine/event.
mux.Handle("/nine/", nine.AdapterHandler(nine.AdapterConfig{
	Secret:  os.Getenv("NINE_ADAPTER_SECRET"),
	Adapter: users{db},
}))

Requests are verified (9in-signature: HMAC-SHA256 over the timestamp, method, path and raw body, 5-minute window, several secrets while you rotate), and every response is signed and bound to its request id. A runnable version is in examples/adapter.

Webhooks

Add an endpoint under Advanced → Webhooks and keep the signing secret it shows once. WebhookHandler verifies each delivery, runs your function once per event, and answers what 9in expects:

mux.Handle("POST /nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
	Secret: os.Getenv("NINE_WEBHOOK_SECRET"),
	Handle: func(ctx context.Context, e *nine.WebhookEvent) error {
		// e.ID, e.EventType, e.CreatedAt, e.Tenant, e.Environment, e.Data
		if e.EventType == "user.created" {
			user, err := e.User()
			if err != nil {
				return err
			}
			return addToCRM(ctx, user)
		}
		return nil // an error answers 500 and 9in retries later
	},
	// Store: a shared nine.Store (Redis SET NX, a SQL unique key) with several instances.
}))

It answers 204 when the event was handled (or already had been), 409 while another delivery of the same event is still running (9in retries later), 401 for a bad signature and 500 when your function failed (the event is released, so the retry handles it). Processed event ids are kept in memory by default (one process); pass a shared Store when you run several.

For your own handler, nine.VerifyWebhookRequest(r, secret) (or nine.VerifyWebhook with the raw body, header and path) verifies and parses an event, and nine.ProcessEventOnce runs a function once per event id. Several secrets are accepted while you rotate.

CLIs, devices and services

The device flow signs users in where there is no browser (a "TV & Device" application):

device, err := nine.NewDeviceAuth(nine.DeviceAuthConfig{Issuer: "https://acme.9in.io", ClientID: "app_tv123"})
code, err := device.Start(ctx)
fmt.Printf("Open %s and enter %s\n", code.VerificationURI, code.UserCode)
tokens, err := device.Wait(ctx, code) // polls until the user approves; nine.ErrAccessDenied, nine.ErrExpiredToken

Services get tokens for themselves with client credentials (a machine-to-machine application), cached until shortly before they expire:

service, err := nine.NewClientCredentials(nine.ClientCredentialsConfig{
	Issuer:       "https://acme.9in.io",
	ClientID:     os.Getenv("NINE_CLIENT_ID"),
	ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
	Audience:     "https://api.acme.com",
})
token, err := service.Token(ctx)
client := service.HTTPClient(nil) // adds "Authorization: Bearer …" to every request

Issuers must use https

Every constructor rejects an issuer that is not https:// (insecure_issuer), so a typo can't send tokens or credentials in clear text. Plain http is accepted for localhost, *.localhost and loopback addresses; for other development hosts (e.g. http://auth:8897 in Docker) set AllowInsecureIssuer: true or NINE_ALLOW_INSECURE_ISSUER=true. Issuers with a query, fragment or credentials are rejected too.

Configuration from the environment

The …ConfigFromEnv functions read NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI, NINE_AUDIENCE, NINE_API_SECRET, NINE_SECRET, NINE_BASE_URL and NINE_ALLOW_INSECURE_ISSUER; nine.Env("WEBHOOK_SECRET") reads any other NINE_* setting (NINE_ADAPTER_SECRET, NINE_WEBHOOK_SECRET). Constructors never read the environment themselves: change the returned config before you pass it on.

Errors

Every failure is a *nine.Error with a Code (invalid_token, insufficient_scope, login_required, invalid_grant, invalid_state, insecure_issuer, …), a Description and, for HTTP errors, a Status. Test for codes with errors.Is and the nine.Err… values, or read the fields with errors.As:

claims, err := verifier.Verify(ctx, token, "orders:write")
switch {
case errors.Is(err, nine.ErrInsufficientScope): // 403
case errors.Is(err, nine.ErrInvalidToken): // 401
case err != nil: // 9in unreachable: errors.As(err, &e) gives e.Code and e.Status
}

The codes are listed in the SDK reference. Network calls have a 10-second timeout by default (pass your own HTTPClient to change it), never follow redirects, and nothing is logged.

Development

go test -race ./...     # unit tests (Go 1.23+)
go vet ./... && staticcheck ./...

The live end-to-end tests run against 9in's test tenants and need their settings (NINE_E2E=1 NINE_E2E_ENV=/path/to/.env.e2e go test -run Live ./...); without them they are skipped. Report bugs in issues.

License

The MIT License (MIT). See LICENSE. 9in is by Cubelet Ltd.

Documentation

Overview

Package nine is the official Go SDK for 9in (https://9in.io): hosted login, OpenID Connect provider and single sign-on.

It uses only the standard library and covers:

  • Signing users in to web apps: WebApp mounts /nine/login, /nine/callback and /nine/logout with an encrypted cookie session and WebApp.RequireUser middleware; WebAppAuth is the flow underneath (authorization code + PKCE, state, nonce, the RFC 9207 iss check, ID token verification, refresh token rotation, logout).
  • Protecting APIs: Verifier checks access tokens locally with every algorithm of 9in's key library, or in hybrid mode (local check plus one cached introspection per token, evicted by webhooks) so revocations apply at once; a shared Store carries the answers and revocations to every process. RequireAuth is the net/http middleware and ClaimsFrom reads the claims.
  • The Management API: ManagementClient (users, sessions, login links, imports).
  • Keeping users in your own database: AdapterHandler serves the adapter protocol v2.
  • Webhooks: VerifyWebhook and WebhookHandler, which processes each event once (with a Store: MemoryStore for one process, Redis or a database for several).
  • CLIs, devices and services: DeviceAuth (RFC 8628) and ClientCredentials.

Every type is safe for concurrent use: create clients once and share them. Every call takes a context.Context; network calls have a 10-second timeout by default, never follow redirects, and nothing is logged. Every failure is an *Error with an OAuth-style Code and an HTTP Status; test for codes with errors.Is and the Err values.

Issuers must use https: http is accepted only for localhost, *.localhost and loopback addresses, unless you allow it (AllowInsecureIssuer, NINE_ALLOW_INSECURE_ISSUER=true).

Guides are at https://9in.io/docs/.

Example

Sign users in to a web app: the routes, an encrypted cookie session and protected pages.

package main

import (
	"fmt"
	"log"
	"net/http"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	// NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_SECRET (32+ characters) and NINE_BASE_URL.
	app, err := nine.NewWebApp(nine.WebAppConfigFromEnv())
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	mux.Handle("/nine/", app) // /nine/login, /nine/signup, /nine/callback, /nine/logout
	mux.Handle("/dashboard", app.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user := nine.UserFrom(r.Context())
		fmt.Fprintf(w, "Hello %s", user.Name)
	})))
	log.Fatal(http.ListenAndServe(":3000", mux))
}

Index

Examples

Constants

View Source
const (
	// SignatureHeader carries t=<unix seconds>,v1=<hex HMAC-SHA256>.
	SignatureHeader = "9in-signature"
	// RequestIDHeader identifies an adapter request; responses are signed over it.
	RequestIDHeader = "9in-request-id"
	// EventIDHeader, EventTypeHeader and DeliveryIDHeader come with webhooks.
	EventIDHeader    = "9in-event-id"
	EventTypeHeader  = "9in-event-type"
	DeliveryIDHeader = "9in-delivery-id"
)

Headers of 9in's signed requests (adapter protocol v2 and webhooks).

View Source
const DefaultTolerance = 5 * time.Minute

DefaultTolerance is how far a signature's timestamp may be from now.

View Source
const OpaquePrefix = "9in_at_"

OpaquePrefix starts 9in's opaque access tokens, which are always introspected.

View Source
const Version = "0.1.0"

Version is the version of this SDK, sent in the User-Agent header.

Variables

View Source
var (
	// ErrInvalidToken: an access token failed verification (401).
	ErrInvalidToken = &Error{Code: "invalid_token", Status: http.StatusUnauthorized}
	// ErrInsufficientScope: the token is valid but lacks a required scope (403).
	ErrInsufficientScope = &Error{Code: "insufficient_scope", Status: http.StatusForbidden}
	// ErrInvalidIDToken: an ID token failed verification.
	ErrInvalidIDToken = &Error{Code: "invalid_id_token", Status: http.StatusUnauthorized}
	// ErrInvalidState: a callback doesn't match a sign-in in progress (another browser, a
	// replay, or it took longer than 15 minutes).
	ErrInvalidState = &Error{Code: "invalid_state", Status: http.StatusBadRequest}
	// ErrInvalidIssuer: the callback's iss parameter isn't your issuer, or the issuer URL
	// is malformed.
	ErrInvalidIssuer = &Error{Code: "invalid_issuer", Status: http.StatusBadRequest}
	// ErrInsecureIssuer: the issuer isn't https (and isn't localhost or loopback).
	ErrInsecureIssuer = &Error{Code: "insecure_issuer"}
	// ErrLoginRequired: there is no session, or it ended.
	ErrLoginRequired = &Error{Code: "login_required", Status: http.StatusUnauthorized}
	// ErrInvalidGrant: 9in refused a code or refresh token (used, expired or revoked).
	ErrInvalidGrant = &Error{Code: "invalid_grant", Status: http.StatusBadRequest}
	// ErrAccessDenied: the user cancelled or declined.
	ErrAccessDenied = &Error{Code: "access_denied", Status: http.StatusBadRequest}
	// ErrInvalidSignature: a webhook or adapter request failed signature verification.
	ErrInvalidSignature = &Error{Code: "invalid_signature", Status: http.StatusUnauthorized}
	// ErrNotFound: the Management API found no such user or session (404; it also
	// matches the API's user_not_found).
	ErrNotFound = &Error{Code: "not_found", Status: http.StatusNotFound}
	// ErrInvalidOptions: a required setting is missing or invalid.
	ErrInvalidOptions = &Error{Code: "invalid_options"}
	// ErrAuthorizationPending: device flow, the user hasn't approved yet.
	ErrAuthorizationPending = &Error{Code: "authorization_pending", Status: http.StatusBadRequest}
	// ErrSlowDown: device flow, polling too fast.
	ErrSlowDown = &Error{Code: "slow_down", Status: http.StatusBadRequest}
	// ErrExpiredToken: device flow, the code expired before the user approved it.
	ErrExpiredToken = &Error{Code: "expired_token", Status: http.StatusBadRequest}

	// ErrInvalidCredentials is what an [Adapter]'s Authenticate returns for an unknown
	// user or a wrong password (9in doesn't tell them apart).
	ErrInvalidCredentials = &Error{Code: "invalid_credentials", Status: http.StatusUnauthorized}
	// ErrUserBlocked is what an [Adapter]'s Authenticate returns for a blocked user.
	ErrUserBlocked = &Error{Code: "blocked", Status: http.StatusForbidden}
)

Errors to test for with errors.Is. They match any *Error with the same Code.

Functions

func AdapterHandler

func AdapterHandler(cfg AdapterConfig) http.Handler

AdapterHandler returns an http.Handler for the adapter protocol v2. Mount it at your adapter's base URL; it serves …/authenticate, …/user and …/event, answering with the same routes, bodies and status codes as the other 9in SDKs:

  • authenticate: 200 {user}, 401 invalid_credentials, 403 blocked
  • user: 200 {user}, 404 not_found
  • event: 204
  • 400 invalid_json or invalid_request for a malformed body, 404 for another route, 500 server_error when the adapter fails

Requests must carry a valid 9in-signature over the method, the path as sent and the raw body (unsigned answers: 401 invalid_signature, 405 for non-POST). Every other answer is signed over "<path>#<9in-request-id>", so it can't be replayed for another request.

Mount it on the path 9in calls (http.StripPrefix is fine: the signed path is read from the request line). It panics when Adapter or the secret is missing.

Example
package main

import (
	"context"
	"net/http"
	"os"

	nine "github.com/9in-io/go-sdk"
)

// myUsers is your user database.
type myUsers struct{}

func (myUsers) Authenticate(ctx context.Context, id nine.Identifier, password string) (*nine.AdapterUser, error) {

	if id.Value != "jane@acme.com" || password != "hunter2" {
		return nil, nine.ErrInvalidCredentials
	}
	return &nine.AdapterUser{ID: "42", Email: "jane@acme.com", EmailVerified: true, Name: "Jane Doe"}, nil
}

func (myUsers) FindUser(ctx context.Context, q nine.UserQuery) (*nine.AdapterUser, error) {
	if q.ID == "42" || (q.Identifier != nil && q.Identifier.Value == "jane@acme.com") {
		return &nine.AdapterUser{ID: "42", Email: "jane@acme.com", Name: "Jane Doe"}, nil
	}
	return nil, nil
}

func (myUsers) OnEvent(ctx context.Context, e *nine.AdapterEvent) error {
	if e.EventType == "otp.requested" {
		return sendCode(ctx, e.Data["channel"], e.Data["to"], e.Data["code"])
	}
	return nil
}

func sendCode(ctx context.Context, channel, to, code any) error { return nil }

func main() {
	// Serves /nine/authenticate, /nine/user and /nine/event.
	http.Handle("/nine/", nine.AdapterHandler(nine.AdapterConfig{
		Secret:  os.Getenv("NINE_ADAPTER_SECRET"),
		Adapter: myUsers{},
	}))
}

func CodeChallenge

func CodeChallenge(verifier string) string

CodeChallenge is the PKCE S256 challenge for a code verifier (RFC 7636): BASE64URL(SHA256(verifier)).

Example
package main

import (
	"fmt"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	fmt.Println(nine.CodeChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"))
}
Output:
E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM

func DefaultScopes

func DefaultScopes() []string

DefaultScopes returns the scopes requested when a configuration names none: an ID token with the profile and email claims, and a refresh token.

func Env

func Env(name string) string

Env returns the value of the NINE_<name> environment variable, or "" when it is unset. Env("ISSUER") and Env("NINE_ISSUER") both read NINE_ISSUER.

The settings this package reads are NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI, NINE_AUDIENCE, NINE_API_SECRET (an API's HMAC secret), NINE_ADAPTER_SECRET, NINE_WEBHOOK_SECRET, NINE_SECRET and NINE_BASE_URL (WebApp), and NINE_ALLOW_INSECURE_ISSUER. Only the …FromEnv functions read them.

func NormalizeIssuer

func NormalizeIssuer(issuer string, allowInsecure bool) (string, error)

NormalizeIssuer checks an issuer URL and returns it without a trailing slash.

Issuers must use https, so a typo can't send tokens or credentials in clear text. Plain http is accepted for localhost, *.localhost and loopback addresses (development), when allowInsecure is true, or when NINE_ALLOW_INSECURE_ISSUER=true. An issuer with a query, a fragment or credentials is refused. The errors are invalid_issuer and insecure_issuer.

Every constructor in this package calls it, so you only need it to check a setting early.

Example
package main

import (
	"fmt"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	issuer, err := nine.NormalizeIssuer("https://acme.9in.io/", false)
	fmt.Println(issuer, err)
	_, err = nine.NormalizeIssuer("http://acme.9in.io", false)
	fmt.Println(err)
	issuer, err = nine.NormalizeIssuer("http://localhost:8787", false)
	fmt.Println(issuer, err)
}
Output:
https://acme.9in.io <nil>
nine: insecure_issuer: issuer must use https (got http://acme.9in.io); plain http is only accepted for localhost
http://localhost:8787 <nil>

func RequireAuth

func RequireAuth(v AccessTokenVerifier, scopes ...string) func(http.Handler) http.Handler

RequireAuth is net/http middleware for your API: it verifies the "Authorization: Bearer …" access token with v, requires every scope given (each argument may hold several, space-separated), and puts the claims in the request context (ClaimsFrom).

A missing or bad token gets 401 invalid_token, a missing scope 403 insufficient_scope, both as JSON with a WWW-Authenticate header (RFC 6750). When verification itself fails (9in unreachable, introspection refused) the answer is 503: that is your server's problem, not the caller's. Use AuthMiddleware to change these answers or to let requests without a token through.

Example
package main

import (
	"fmt"
	"log"
	"net/http"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	verifier, err := nine.NewVerifier(nine.VerifierConfigFromEnv()) // NINE_ISSUER, NINE_AUDIENCE…
	if err != nil {
		log.Fatal(err)
	}
	orders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		claims := nine.ClaimsFrom(r.Context())
		if claims.IsMachine() { // a client-credentials token: no user
			http.Error(w, "users only", http.StatusForbidden)
			return
		}
		fmt.Fprintf(w, "orders of %s", claims.Subject())
	})
	http.Handle("GET /api/orders", nine.RequireAuth(verifier, "orders:read")(orders))
}

func SafeReturnPath

func SafeReturnPath(path string) string

SafeReturnPath returns path when it is a path on your own site ("/dashboard?tab=1"), and "" for anything that could send the user elsewhere: absolute URLs, protocol-relative "//host" and "/\host", or control characters.

Example
package main

import (
	"fmt"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	for _, p := range []string{"/dashboard?tab=2", "https://evil.example", "//evil.example", "/\\evil.example"} {
		fmt.Printf("%q\n", nine.SafeReturnPath(p))
	}
}
Output:
"/dashboard?tab=2"
""
""
""

func SignPayload

func SignPayload(secret, method, path string, body []byte) string

SignPayload signs a request or response the way 9in does, with the current time: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<METHOD>.<path>.<body>")>. It returns the 9in-signature header value. Adapter responses are signed over "<path>#<request id>".

func SignPayloadAt

func SignPayloadAt(secret, method, path string, body []byte, at time.Time) string

SignPayloadAt is SignPayload with a given time.

Example
package main

import (
	"fmt"
	"time"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	body := []byte(`{"identifier":{"type":"email","value":"jane@acme.com"},"password":"hunter2"}`)
	header := nine.SignPayloadAt("adapter_secret_test", "POST", "/nine/authenticate", body, time.Unix(1762682400, 0))
	fmt.Println(header)
}
Output:
t=1762682400,v1=f8c341feb9ffa2698aa90a3e762f7108a324e503aa260bbc305e8ba3be9ca49c

func VerifySignature

func VerifySignature(secrets []string, header, method, path string, body []byte, tolerance time.Duration) error

VerifySignature checks a 9in-signature header against a request's method, path and raw body, with any of secrets (several while you rotate) and a timestamp tolerance (0 means DefaultTolerance). It fails with invalid_signature (Status 401), whose Description is the reason: missing, malformed, expired or mismatch.

Example
package main

import (
	"fmt"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	body := []byte(`{"id":"42"}`)
	header := nine.SignPayload("new-secret", "POST", "/nine/user", body)
	// Several secrets while you rotate; 0 means the default 5-minute tolerance.
	err := nine.VerifySignature([]string{"new-secret", "old-secret"}, header, "POST", "/nine/user", body, 0)
	fmt.Println(err)
	err = nine.VerifySignature([]string{"other"}, header, "POST", "/nine/user", body, 0)
	fmt.Println(err)
}
Output:
<nil>
nine: invalid_signature: mismatch

func WebhookHandler

func WebhookHandler(cfg WebhookConfig) http.Handler

WebhookHandler returns an http.Handler for your webhook endpoint. It answers:

  • 204 when the event was handled, or had already been (a retry or redelivery);
  • 409 while another delivery of the same event is still being handled (9in retries);
  • 401 for a bad signature, 400 for a body that isn't an event, 405 for non-POST;
  • 500 when Handle failed (the event id is released, so 9in's retry handles it), or when the Verifier couldn't record a revocation in its shared Store.

It panics when no secret is given (a configuration error, found at startup).

Example
package main

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

	nine "github.com/9in-io/go-sdk"
)

func main() {
	http.Handle("POST /nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
		Secret: os.Getenv("NINE_WEBHOOK_SECRET"),
		// Called once per event; return an error to have 9in retry later.
		Handle: func(ctx context.Context, e *nine.WebhookEvent) error {
			switch e.EventType {
			case "user.created":
				user, err := e.User()
				if err != nil {
					return err
				}
				fmt.Println("welcome", user.Email)
			case "user.deleted":
				fmt.Println("goodbye", e.UserID())
			}
			return nil
		},
		// Store: a shared nine.Store (Redis SET NX…) when you run several instances.
	}))
}

func WithClaims

func WithClaims(ctx context.Context, claims Claims) context.Context

WithClaims returns a copy of ctx carrying claims (what RequireAuth does; handy in tests).

func WriteAuthError

func WriteAuthError(w http.ResponseWriter, err error, scopes ...string)

WriteAuthError writes the answer for a failed token check: 401 invalid_token, 403 insufficient_scope (naming the required scopes), or 503 for anything else, as JSON with a WWW-Authenticate header.

Types

type AccessTokenVerifier

type AccessTokenVerifier interface {
	Verify(ctx context.Context, token string, scopes ...string) (Claims, error)
}

AccessTokenVerifier verifies bearer tokens. *Verifier implements it; so can a fake in your tests.

type Adapter

type Adapter interface {
	// Authenticate checks a password. Return the user, or ErrInvalidCredentials (or a nil
	// user) for an unknown user or a wrong password, or ErrUserBlocked (or a user with
	// Blocked set) for a blocked one. Any other error answers 500.
	Authenticate(ctx context.Context, id Identifier, password string) (*AdapterUser, error)
	// FindUser looks a user up by id or identifier. Return a nil user (or ErrNotFound)
	// when there is none.
	FindUser(ctx context.Context, query UserQuery) (*AdapterUser, error)
	// OnEvent receives notifications, including otp.requested when you deliver one-time
	// codes yourself.
	OnEvent(ctx context.Context, event *AdapterEvent) error
}

Adapter is your user database, as 9in sees it (adapter protocol v2).

type AdapterConfig

type AdapterConfig struct {
	// Adapter is your user database (required).
	Adapter Adapter
	// Secret is the connection's shared secret (Connections → User database;
	// NINE_ADAPTER_SECRET). Responses are signed with it.
	Secret string
	// Secrets are more secrets accepted while you rotate.
	Secrets []string
	// Tolerance is the signature timestamp tolerance. Default 5 minutes.
	Tolerance time.Duration
	// OnError is told about adapter errors that were answered with 500. Optional.
	OnError func(r *http.Request, err error)
}

AdapterConfig configures AdapterHandler.

type AdapterEvent

type AdapterEvent struct {
	ID        string         `json:"id"`
	EventType string         `json:"event_type"`
	CreatedAt time.Time      `json:"created_at"`
	Data      map[string]any `json:"data"`
}

AdapterEvent is what 9in posts to …/event. Data["user_id"] is your own user id. otp.requested carries user_id, channel ("email" or "sms"), to, code, purpose ("login" or "password_reset") and expires_at; user.updated and user.password_changed carry user_id and fields.

func (*AdapterEvent) UserID

func (e *AdapterEvent) UserID() string

UserID is data.user_id: your own user id, or "".

type AdapterUser

type AdapterUser struct {
	// ID is your user id (required, up to 256 characters).
	ID                  string         `json:"id"`
	Email               string         `json:"email,omitempty"`
	EmailVerified       bool           `json:"email_verified,omitempty"`
	PhoneNumber         string         `json:"phone_number,omitempty"` // E.164
	PhoneNumberVerified bool           `json:"phone_number_verified,omitempty"`
	Username            string         `json:"username,omitempty"`
	Name                string         `json:"name,omitempty"`
	GivenName           string         `json:"given_name,omitempty"`
	FamilyName          string         `json:"family_name,omitempty"`
	Picture             string         `json:"picture,omitempty"` // https URL
	Locale              string         `json:"locale,omitempty"`
	Zoneinfo            string         `json:"zoneinfo,omitempty"`
	Birthdate           string         `json:"birthdate,omitempty"` // YYYY-MM-DD
	Blocked             bool           `json:"blocked,omitempty"`
	Metadata            map[string]any `json:"metadata,omitempty"`
}

AdapterUser is a user from your database, in the shape 9in expects (OpenID Connect claim names). Empty fields are left out. Metadata is stored on the 9in user.

type AuthMiddleware

type AuthMiddleware struct {
	// Verifier checks the tokens (required).
	Verifier AccessTokenVerifier
	// Scopes must all be granted.
	Scopes []string
	// Optional lets requests without a bearer token through, without claims. A bearer
	// token that is present must still be valid.
	Optional bool
	// OnError writes the answer when verification fails. Default: 401, 403 or 503 JSON.
	OnError func(w http.ResponseWriter, r *http.Request, err error)
}

AuthMiddleware is RequireAuth with more choices.

func (AuthMiddleware) Wrap

func (m AuthMiddleware) Wrap(next http.Handler) http.Handler

Wrap returns next behind the middleware.

type Claims

type Claims map[string]any

Claims are the claims of a verified token (or an introspection answer), as 9in sent them: numbers are float64, lists []any, objects map[string]any. The methods read the common ones.

Example
package main

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	var claims nine.Claims
	_ = json.NewDecoder(strings.NewReader(`{"sub":"usr_8k2","client_id":"app_1","scope":"openid orders:read","exp":1794203600,"aud":"https://api.acme.com"}`)).Decode(&claims)
	fmt.Println(claims.Subject(), claims.Scopes(), claims.HasScope("orders:read"), claims.Audience(), claims.ExpiresAt().UTC().Format(time.RFC3339))
}
Output:
usr_8k2 [openid orders:read] true [https://api.acme.com] 2026-11-09T05:53:20Z

func ClaimsFrom

func ClaimsFrom(ctx context.Context) Claims

ClaimsFrom returns the access token claims RequireAuth put in the request context, or nil.

func (Claims) Audience

func (c Claims) Audience() []string

Audience is the aud claim (a single audience is returned as a one-item list).

func (Claims) Bool

func (c Claims) Bool(name string) bool

Bool returns a boolean claim, or false.

func (Claims) ClientID

func (c Claims) ClientID() string

ClientID is the client_id claim: the application the token was issued to.

func (Claims) ExpiresAt

func (c Claims) ExpiresAt() time.Time

ExpiresAt is the exp claim as a time (the zero time when absent).

func (Claims) HasScope

func (c Claims) HasScope(scope string) bool

HasScope reports whether the scope claim contains scope.

func (Claims) Int

func (c Claims) Int(name string) (int64, bool)

Int returns a numeric claim (exp, iat, auth_time…) and whether it is a number.

func (Claims) IsMachine

func (c Claims) IsMachine() bool

IsMachine reports whether this is a client-credentials token: its subject is the application itself (sub equals client_id) and it has no session.

func (Claims) Issuer

func (c Claims) Issuer() string

Issuer is the iss claim.

func (Claims) Scopes

func (c Claims) Scopes() []string

Scopes are the scopes in the space-separated scope claim.

func (Claims) SessionID

func (c Claims) SessionID() string

SessionID is the sid claim (absent for client-credentials tokens).

func (Claims) String

func (c Claims) String(name string) string

String returns a string claim, or "".

func (Claims) Strings

func (c Claims) Strings(name string) []string

Strings returns a claim that is a string or a list of strings (aud, amr).

func (Claims) Subject

func (c Claims) Subject() string

Subject is the sub claim: the user's id, or the client ID for a client-credentials token.

func (Claims) Time

func (c Claims) Time(name string) time.Time

Time returns a claim holding unix seconds (exp, iat, auth_time…) as a time, or the zero time.

func (Claims) TokenID

func (c Claims) TokenID() string

TokenID is the jti claim.

type ClientCredentials

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

ClientCredentials gets access tokens for a service itself (no user) with the client credentials grant, and caches each until shortly before it expires. Concurrent callers share one request. Safe for concurrent use.

Example
package main

import (
	"log"
	"net/http"
	"os"
	"time"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	service, err := nine.NewClientCredentials(nine.ClientCredentialsConfig{
		Issuer:       "https://acme.9in.io",
		ClientID:     os.Getenv("NINE_CLIENT_ID"),
		ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
		Audience:     "https://api.acme.com",
	})
	if err != nil {
		log.Fatal(err)
	}
	// Every request carries a cached, renewed-before-expiry access token.
	client := service.HTTPClient(&http.Client{Timeout: 10 * time.Second})
	res, err := client.Get("https://api.acme.com/reports")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
}

func NewClientCredentials

func NewClientCredentials(cfg ClientCredentialsConfig) (*ClientCredentials, error)

NewClientCredentials returns a ClientCredentials token source.

func (*ClientCredentials) HTTPClient

func (c *ClientCredentials) HTTPClient(base *http.Client) *http.Client

HTTPClient returns a copy of base (or of http.DefaultClient) that adds "Authorization: Bearer <token>" to every request. Use it only for the API the token is for.

func (*ClientCredentials) Invalidate

func (c *ClientCredentials) Invalidate()

Invalidate forgets the cached token, so the next call gets a new one (after a 401 from your API, say).

func (*ClientCredentials) Token

func (c *ClientCredentials) Token(ctx context.Context) (string, error)

Token returns a valid access token, from the cache or a new client-credentials request.

type ClientCredentialsConfig

type ClientCredentialsConfig struct {
	// Issuer is your tenant's issuer.
	Issuer string
	// ClientID and ClientSecret are a confidential (machine-to-machine) application.
	ClientID     string
	ClientSecret string
	// Audience is the API to call; leave empty for the Management API.
	Audience string
	// Scopes to request; empty means every scope the application was granted for Audience.
	Scopes []string
	// HTTPClient is used for the token requests. Default: a client with a 10-second timeout.
	HTTPClient *http.Client
	// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
	AllowInsecureIssuer bool
}

ClientCredentialsConfig configures a ClientCredentials token source.

func ClientCredentialsConfigFromEnv

func ClientCredentialsConfigFromEnv() ClientCredentialsConfig

ClientCredentialsConfigFromEnv returns a ClientCredentialsConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_AUDIENCE and NINE_ALLOW_INSECURE_ISSUER.

type ClientCredentialsOptions

type ClientCredentialsOptions struct {
	// Audience is the API to get a token for; leave empty for the Management API.
	Audience string
	// Scope is space-separated; empty means every scope the application was granted.
	Scope string
}

ClientCredentialsOptions are the parameters of a client-credentials request.

type DeviceAuth

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

DeviceAuth signs users in on devices without a browser or keyboard (CLIs, TVs) with the device authorization grant (RFC 8628): the device shows a short code, the user enters it on their phone or computer, and the device receives tokens once they approve. Safe for concurrent use.

code, _ := device.Start(ctx)
fmt.Printf("Open %s and enter %s\n", code.VerificationURI, code.UserCode)
tokens, err := device.Wait(ctx, code)
Example
package main

import (
	"context"
	"fmt"
	"log"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	device, err := nine.NewDeviceAuth(nine.DeviceAuthConfig{Issuer: "https://acme.9in.io", ClientID: "app_tv123"})
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	code, err := device.Start(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Open %s and enter %s\n", code.VerificationURI, code.UserCode)
	tokens, err := device.Wait(ctx, code) // polls until the user approves
	if err != nil {
		log.Fatal(err) // access_denied, expired_token…
	}
	fmt.Println("signed in as", tokens.Claims.Subject())
}

func NewDeviceAuth

func NewDeviceAuth(cfg DeviceAuthConfig) (*DeviceAuth, error)

NewDeviceAuth returns a DeviceAuth.

func (*DeviceAuth) EnsureFresh

func (d *DeviceAuth) EnsureFresh(ctx context.Context, tokens *TokenSet, leeway time.Duration) (*TokenSet, error)

EnsureFresh returns tokens unchanged while valid for at least leeway, else refreshed.

func (*DeviceAuth) Poll

func (d *DeviceAuth) Poll(ctx context.Context, code *DeviceCode) (*TokenSet, error)

Poll asks once whether the user has approved. It fails with authorization_pending (keep polling), slow_down (poll less often), access_denied (the user declined) or expired_token (start over). On success a returned ID token is verified.

func (*DeviceAuth) Refresh

func (d *DeviceAuth) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)

Refresh exchanges a refresh token (9in rotates it: keep the new one).

func (*DeviceAuth) Revoke

func (d *DeviceAuth) Revoke(ctx context.Context, token, hint string) error

Revoke revokes a refresh token (hint "refresh_token", the default) or an access token.

func (*DeviceAuth) Start

func (d *DeviceAuth) Start(ctx context.Context) (*DeviceCode, error)

Start asks 9in for a device code and a user code.

func (*DeviceAuth) UserInfo

func (d *DeviceAuth) UserInfo(ctx context.Context, accessToken string) (Claims, error)

UserInfo returns the user's current claims from the userinfo endpoint.

func (*DeviceAuth) Wait

func (d *DeviceAuth) Wait(ctx context.Context, code *DeviceCode) (*TokenSet, error)

Wait polls every code.Interval seconds until the user approves (and returns the tokens), declines (access_denied), the code expires (expired_token) or ctx ends. It slows down by 5 seconds whenever 9in asks it to.

type DeviceAuthConfig

type DeviceAuthConfig struct {
	// Issuer is your tenant's issuer.
	Issuer string
	// ClientID is a "TV & Device" application (a public client with the device code grant).
	ClientID string
	// ClientSecret is only for confidential applications that enable the device grant.
	ClientSecret string
	// Scopes default to openid, profile and offline_access.
	Scopes []string
	// Audience is an API identifier, to get access tokens for that API.
	Audience string
	// Leeway is the clock skew allowed when checking ID tokens. Default 30 seconds.
	Leeway time.Duration
	// HTTPClient is used for every call to 9in. Default: a client with a 10-second timeout.
	HTTPClient *http.Client
	// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
	AllowInsecureIssuer bool
}

DeviceAuthConfig configures a DeviceAuth.

type DeviceCode

type DeviceCode struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	// ExpiresIn and Interval are seconds, as 9in sent them.
	ExpiresIn int `json:"expires_in"`
	Interval  int `json:"interval"`
	// ExpiresAt is when the code stops working.
	ExpiresAt time.Time `json:"expires_at"`
}

DeviceCode is what DeviceAuth.Start returns: show the user VerificationURI and UserCode (or a QR code of VerificationURIComplete, which fills the code in).

type Discovery

type Discovery struct {
	Issuer                                     string   `json:"issuer"`
	AuthorizationEndpoint                      string   `json:"authorization_endpoint"`
	TokenEndpoint                              string   `json:"token_endpoint"`
	UserinfoEndpoint                           string   `json:"userinfo_endpoint"`
	JWKSURI                                    string   `json:"jwks_uri"`
	RevocationEndpoint                         string   `json:"revocation_endpoint,omitempty"`
	IntrospectionEndpoint                      string   `json:"introspection_endpoint,omitempty"`
	EndSessionEndpoint                         string   `json:"end_session_endpoint,omitempty"`
	DeviceAuthorizationEndpoint                string   `json:"device_authorization_endpoint,omitempty"`
	AuthorizationResponseIssParameterSupported bool     `json:"authorization_response_iss_parameter_supported,omitempty"`
	IDTokenSigningAlgValuesSupported           []string `json:"id_token_signing_alg_values_supported,omitempty"`
	ScopesSupported                            []string `json:"scopes_supported,omitempty"`
}

Discovery is your tenant's OpenID Connect discovery document (<issuer>/.well-known/openid-configuration), with the fields this package uses.

type Error

type Error struct {
	// Code is the error code, e.g. "invalid_token".
	Code string
	// Description says what went wrong, for people (never contains a token or secret).
	Description string
	// Status is the HTTP status: the one 9in answered with, or the one to answer with
	// (401 for invalid_token, 403 for insufficient_scope). 0 when there is none.
	Status int
	// Details is the "details" member of a Management API error body, when there is one
	// (for invalid_user, a list of {path, message}).
	Details any
	// contains filtered or unexported fields
}

Error is the error every failure in this package is reported with. Code is an OAuth-style error code ("invalid_token", "insufficient_scope", "invalid_grant", "insecure_issuer", …), passed through unchanged when it comes from 9in. Status is the HTTP status that goes with it (0 when there is none).

Use errors.As to read it, or errors.Is with one of the Err values below to test for a code:

if errors.Is(err, nine.ErrInsufficientScope) { … }

var e *nine.Error
if errors.As(err, &e) && e.Code == "identifier_taken" { … }
Example
package main

import (
	"errors"
	"fmt"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	err := error(&nine.Error{Code: "insufficient_scope", Description: "missing orders:write", Status: 403})
	var e *nine.Error
	if errors.As(err, &e) {
		fmt.Println(e.Code, e.Status)
	}
	fmt.Println(errors.Is(err, nine.ErrInsufficientScope), errors.Is(err, nine.ErrInvalidToken))
}
Output:
insufficient_scope 403
true false

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is an *Error with the same Code, so that errors.Is(err, nine.ErrInvalidToken) matches every invalid_token error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause (a network error, a context error), if any.

type EventDeduplicator

type EventDeduplicator struct {
	// Store keeps the ids (required). Its Add must be atomic.
	Store Store
	// TTL is how long a processed id is remembered. Default 3 days.
	TTL time.Duration
	// LockTTL is how long a running handler holds the id before another delivery may
	// take over. Default 5 minutes.
	LockTTL time.Duration
	// Prefix starts every key. Default "9in:event:".
	Prefix string
}

EventDeduplicator runs a handler at most once per event id. 9in keeps the id on every retry and redelivery, and retries until it gets a 2xx (for about a day).

func (*EventDeduplicator) Process

func (d *EventDeduplicator) Process(ctx context.Context, eventID string, handler func(context.Context) error) (ProcessStatus, error)

Process claims eventID and runs handler:

  • Processed: first delivery, handler succeeded (the id is then remembered for TTL).
  • Duplicate: already processed; handler not run.
  • InProgress: another delivery is running it; handler not run.
  • handler failed (or panicked): the claim is released so 9in's retry runs it again, and the error is returned (or the panic continues).

When the handler succeeded but marking the id as done failed, it returns Processed with that error.

type EventStore deprecated

type EventStore = Store

EventStore is the Store that EventDeduplicator and WebhookHandler keep event ids in.

Deprecated: use Store, the same interface (renamed in 0.2.0, when the hybrid Verifier started using it too).

type Identifier

type Identifier struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

Identifier is how a user signs in: Type is "email", "username" or "phone".

type ImportIdentity

type ImportIdentity struct {
	Connection string `json:"connection"` // e.g. social:google
	Subject    string `json:"subject"`
}

ImportIdentity is a linked sign-in carried over by an import.

type ImportOptions

type ImportOptions struct {
	// OnConflict is "skip" (the default) or "update" when a user already exists.
	OnConflict string
	// Source labels the import in the activity log.
	Source string
}

ImportOptions are the options of ImportUsers.

type ImportResult

type ImportResult struct {
	Index int  `json:"index"`
	OK    bool `json:"ok"`
	// Status is "created", "updated", "skipped" or "failed".
	Status  string `json:"status"`
	ID      string `json:"id,omitempty"`
	Reason  string `json:"reason,omitempty"`
	Error   string `json:"error,omitempty"`
	Details any    `json:"details,omitempty"`
}

ImportResult is the outcome of one import record, in the order given.

type ImportUser

type ImportUser struct {
	// ID keeps the id from your old system (letters, digits and | _ . : @ + -, max 128).
	ID string `json:"id,omitempty"`
	NewUser
	Identities  []ImportIdentity `json:"identities,omitempty"`
	CreatedAt   *time.Time       `json:"created_at,omitempty"`
	LastLoginAt *time.Time       `json:"last_login_at,omitempty"`
}

ImportUser is one record for ImportUsers: the fields of NewUser plus what an import may carry over.

type ListUsersOptions

type ListUsersOptions struct {
	// Query matches email, username, phone number and name (substring) or an exact id.
	Query string
	// Cursor is the NextCursor of the previous page.
	Cursor string
	// Limit is 1 to 200 (default 50).
	Limit int
}

ListUsersOptions page and search the user list.

type Login

type Login struct {
	URL     string
	Pending *PendingLogin
}

Login is a sign-in that has started: send the browser to URL and keep Pending until the callback.

type LoginLink struct {
	URL       string    `json:"url"`
	ExpiresAt time.Time `json:"expires_at"`
}

LoginLink is a single-use URL that signs the user in.

type LoginLinkOptions

type LoginLinkOptions struct {
	// ReturnTo must be a registered callback URL of one of your applications, or a path
	// on the login domain.
	ReturnTo string
	// TTL is how long the link works (whole seconds).
	TTL time.Duration
}

LoginLinkOptions are the options of CreateLoginLink.

type LoginOptions

type LoginOptions struct {
	// ReturnTo is a path on your site to come back to afterwards ("/dashboard"). Only a
	// same-site path is kept ([SafeReturnPath]); it comes back in [TokenSet].ReturnTo.
	ReturnTo string
	// Screen "signup" opens the sign-up form (prompt=create).
	Screen string
	// Prompt is "login" (sign in again), "consent", "select_account", "none" (no UI:
	// fails with login_required) or "create".
	Prompt string
	// LoginHint prefills the identifier.
	LoginHint string
	// Locale picks the language of the hosted pages (ui_locales), e.g. "de".
	Locale string
	// RedirectURI overrides the configured callback URL for this sign-in.
	RedirectURI string
	// Params are extra authorization parameters (max_age, …). They never replace
	// response_type, client_id, redirect_uri, scope, state, nonce or PKCE.
	Params map[string]string
}

LoginOptions are the choices for one sign-in.

type LogoutOptions

type LogoutOptions struct {
	// IDTokenHint identifies the session's application (an expired ID token is fine).
	IDTokenHint string
	// PostLogoutRedirectURI is where 9in sends the user afterwards: one of the
	// application's allowed logout URLs.
	PostLogoutRedirectURI string
	// State is added to that redirect.
	State string
}

LogoutOptions are the parameters of the end-session URL.

type MFAState

type MFAState struct {
	Enabled           bool       `json:"enabled"`
	EnabledAt         *time.Time `json:"enabled_at,omitempty"`
	RecoveryCodesLeft *int       `json:"recovery_codes_left,omitempty"`
}

MFAState is a user's two-factor state.

type ManagedIdentity

type ManagedIdentity struct {
	Connection string         `json:"connection"`
	Subject    string         `json:"subject"`
	Profile    map[string]any `json:"profile"`
	CreatedAt  time.Time      `json:"created_at"`
}

ManagedIdentity is a linked sign-in of a user (social:google, enterprise:<id>, adapter…).

type ManagedSession

type ManagedSession struct {
	SID        string    `json:"sid"`
	UserID     string    `json:"user_id"`
	AuthTime   time.Time `json:"auth_time"`
	AMR        []string  `json:"amr"`
	IP         string    `json:"ip"`
	UserAgent  string    `json:"user_agent"`
	CreatedAt  time.Time `json:"created_at"`
	LastSeenAt time.Time `json:"last_seen_at"`
	ExpiresAt  time.Time `json:"expires_at"`
}

ManagedSession is an active sign-in session; SID is the sid claim of its tokens.

type ManagedUser

type ManagedUser struct {
	ID                  string         `json:"id"`
	Email               string         `json:"email"`
	EmailVerified       bool           `json:"email_verified"`
	PhoneNumber         string         `json:"phone_number"`
	PhoneNumberVerified bool           `json:"phone_number_verified"`
	Username            string         `json:"username"`
	PreferredUsername   string         `json:"preferred_username"`
	Name                string         `json:"name"`
	GivenName           string         `json:"given_name"`
	MiddleName          string         `json:"middle_name"`
	FamilyName          string         `json:"family_name"`
	Nickname            string         `json:"nickname"`
	Gender              string         `json:"gender"`
	Website             string         `json:"website"`
	Picture             string         `json:"picture"`
	Locale              string         `json:"locale"`
	Zoneinfo            string         `json:"zoneinfo"`
	Birthdate           string         `json:"birthdate"`
	Blocked             bool           `json:"blocked"`
	Metadata            map[string]any `json:"metadata"`
	CreatedAt           time.Time      `json:"created_at"`
	UpdatedAt           time.Time      `json:"updated_at"`
	LastLoginAt         *time.Time     `json:"last_login_at"`
	LoginCount          int            `json:"login_count"`
}

ManagedUser is a user as the Management API and webhooks send it.

type ManagementClient

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

ManagementClient calls the Management API (/api/v1) of one tenant environment: users, sessions, login links and imports. It gets client-credentials tokens itself, one per management scope (so an application granted only some scopes works), and caches each until shortly before it expires. Safe for concurrent use.

Wire data uses 9in's snake_case names in both directions. Errors are *Error with the API's error code (not_found, identifier_taken, invalid_user…), Status and Details.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	m, err := nine.NewManagementClient(nine.ManagementConfig{
		Issuer:       "https://acme.9in.io",
		ClientID:     os.Getenv("NINE_CLIENT_ID"), // an application with management scopes
		ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
	})
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	user, err := m.CreateUser(ctx, nine.NewUser{Email: "jane@acme.com", EmailVerified: true, Password: "a long passphrase"})
	var e *nine.Error
	if errors.As(err, &e) && e.Code == "identifier_taken" {
		user, err = m.FindUserByEmail(ctx, "jane@acme.com")
	}
	if err != nil {
		log.Fatal(err)
	}
	_, _ = m.UpdateUser(ctx, user.ID, nine.UserChanges{"metadata": map[string]any{"plan": "pro"}})
	link, _ := m.CreateLoginLink(ctx, user.ID, nine.LoginLinkOptions{ReturnTo: "https://app.acme.com/nine/callback", TTL: 10 * time.Minute})
	fmt.Println(link.URL)
}

func NewManagementClient

func NewManagementClient(cfg ManagementConfig) (*ManagementClient, error)

NewManagementClient returns a ManagementClient.

func (*ManagementClient) BlockUser

func (m *ManagementClient) BlockUser(ctx context.Context, id string) (*ManagedUser, error)

BlockUser blocks a user: their sessions end and their tokens stop working.

func (m *ManagementClient) CreateLoginLink(ctx context.Context, id string, opts LoginLinkOptions) (*LoginLink, error)

CreateLoginLink creates a single-use URL that signs the user in (magic links, handing a signed-in user over from your app). Two-factor authentication still applies.

func (*ManagementClient) CreateUser

func (m *ManagementClient) CreateUser(ctx context.Context, user NewUser) (*ManagedUser, error)

CreateUser creates a user. A taken email, phone number or username fails with identifier_taken (409); bad fields with invalid_user (400, with Details).

func (*ManagementClient) DeleteUser

func (m *ManagementClient) DeleteUser(ctx context.Context, id string) error

DeleteUser deletes a user.

func (*ManagementClient) FindUser

func (m *ManagementClient) FindUser(ctx context.Context, field, value string) (*ManagedUser, error)

FindUser looks a user up by field "email", "phone_number" (E.164) or "username". Emails and usernames match case-insensitively. No match fails with not_found (404).

func (*ManagementClient) FindUserByEmail

func (m *ManagementClient) FindUserByEmail(ctx context.Context, email string) (*ManagedUser, error)

FindUserByEmail is FindUser(ctx, "email", email).

func (*ManagementClient) GetUser

func (m *ManagementClient) GetUser(ctx context.Context, id string) (*UserDetail, error)

GetUser returns a user with their identities, active sessions and two-factor state. An unknown id fails with not_found (404): test with errors.Is(err, nine.ErrNotFound).

func (*ManagementClient) ImportUsers

func (m *ManagementClient) ImportUsers(ctx context.Context, users []ImportUser, opts ImportOptions) ([]ImportResult, error)

ImportUsers imports up to 500 users per call (50 with plain-text passwords). Records may keep their old id and carry password hashes, social identities and original dates. Results are per record, in order; one bad record doesn't stop the others.

func (*ManagementClient) ListUserSessions

func (m *ManagementClient) ListUserSessions(ctx context.Context, id string) ([]ManagedSession, error)

ListUserSessions returns the user's active sessions, most recently used first.

func (*ManagementClient) ListUsers

func (m *ManagementClient) ListUsers(ctx context.Context, opts ListUsersOptions) (*UserList, error)

ListUsers returns a page of users, newest first.

func (*ManagementClient) RevokeSession

func (m *ManagementClient) RevokeSession(ctx context.Context, sid string) error

RevokeSession ends one session (its sid) and every token issued under it.

func (*ManagementClient) RevokeUserSessions

func (m *ManagementClient) RevokeUserSessions(ctx context.Context, id string) (int, error)

RevokeUserSessions signs the user out everywhere and returns how many sessions ended.

func (*ManagementClient) UnblockUser

func (m *ManagementClient) UnblockUser(ctx context.Context, id string) (*ManagedUser, error)

UnblockUser lets a blocked user sign in again.

func (*ManagementClient) UpdateUser

func (m *ManagementClient) UpdateUser(ctx context.Context, id string, changes UserChanges) (*ManagedUser, error)

UpdateUser changes only the fields given and returns the updated user.

type ManagementConfig

type ManagementConfig struct {
	// Issuer is your tenant's issuer: https://acme.9in.io for production users,
	// https://acme-sandbox.9in.io for the sandbox's, or your custom domain.
	Issuer string
	// ClientID and ClientSecret are a confidential application that was given management
	// scopes (Applications → app → API Access → Management API).
	ClientID     string
	ClientSecret string
	// HTTPClient is used for every call. Default: a client with a 10-second timeout.
	HTTPClient *http.Client
	// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
	AllowInsecureIssuer bool
}

ManagementConfig configures a ManagementClient.

func ManagementConfigFromEnv

func ManagementConfigFromEnv() ManagementConfig

ManagementConfigFromEnv returns a ManagementConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET and NINE_ALLOW_INSECURE_ISSUER.

type MemoryEventStore deprecated

type MemoryEventStore = MemoryStore

MemoryEventStore is the in-memory Store.

Deprecated: use MemoryStore (renamed in 0.2.0).

type MemoryStore added in v0.2.0

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

MemoryStore is an in-memory Store for one process: tests, a single server, or the default of WebhookHandler. It is safe for concurrent use.

func NewMemoryEventStore deprecated

func NewMemoryEventStore() *MemoryStore

NewMemoryEventStore returns an empty in-memory Store.

Deprecated: use NewMemoryStore (renamed in 0.2.0).

func NewMemoryStore added in v0.2.0

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty MemoryStore.

func (*MemoryStore) Add added in v0.2.0

func (s *MemoryStore) Add(_ context.Context, key, value string, ttl time.Duration) (bool, error)

Add implements Store.

func (*MemoryStore) Delete added in v0.2.0

func (s *MemoryStore) Delete(_ context.Context, key string) error

Delete implements Store.

func (*MemoryStore) Get added in v0.2.0

func (s *MemoryStore) Get(_ context.Context, key string) (string, bool, error)

Get implements Store.

func (*MemoryStore) Set added in v0.2.0

func (s *MemoryStore) Set(_ context.Context, key, value string, ttl time.Duration) error

Set implements Store.

type Mode

type Mode string

Mode is how a Verifier checks access tokens: the trade-off between speed and how quickly a revocation takes effect.

const (
	// ModeLocal checks the signature and claims only. No calls to 9in per request; a
	// revoked token keeps working until it expires.
	ModeLocal Mode = "local"
	// ModeHybrid checks locally, then asks 9in once per token (introspection) and caches
	// the answer until a webhook says otherwise ([Verifier.HandleEvent]) or CacheTTL
	// passes. A refusal is cached until the token expires.
	ModeHybrid Mode = "hybrid"
	// ModeIntrospect asks 9in about every token on every call.
	ModeIntrospect Mode = "introspect"
)

type MultiGetter added in v0.2.0

type MultiGetter interface {
	// GetMany returns the values of keys and whether each exists, in the same order.
	GetMany(ctx context.Context, keys []string) (values []string, ok []bool, err error)
}

MultiGetter is an optional method of a Store that reads several keys in one round trip (Redis MGET). When the store has it, a hybrid Verifier reads a cached answer's revocation markers with one call instead of one per marker.

type NewUser

type NewUser struct {
	Email               string `json:"email,omitempty"`
	EmailVerified       bool   `json:"email_verified,omitempty"`
	PhoneNumber         string `json:"phone_number,omitempty"` // E.164, e.g. +447700900123
	PhoneNumberVerified bool   `json:"phone_number_verified,omitempty"`
	Username            string `json:"username,omitempty"`
	Name                string `json:"name,omitempty"`
	GivenName           string `json:"given_name,omitempty"`
	FamilyName          string `json:"family_name,omitempty"`
	Picture             string `json:"picture,omitempty"`
	Locale              string `json:"locale,omitempty"`
	Zoneinfo            string `json:"zoneinfo,omitempty"`
	Birthdate           string `json:"birthdate,omitempty"` // YYYY-MM-DD
	Blocked             bool   `json:"blocked,omitempty"`
	// Metadata is stored on the user; custom profile fields live in metadata.fields.
	Metadata map[string]any `json:"metadata,omitempty"`
	// Password is a plain password (hashed with argon2id), or give PasswordHash.
	Password string `json:"password,omitempty"`
	// PasswordHash is an existing bcrypt, argon2, PBKDF2 or Firebase scrypt hash.
	PasswordHash string `json:"password_hash,omitempty"`
}

NewUser is a user to create. At least one of Email, PhoneNumber or Username is required.

type PendingLogin

type PendingLogin struct {
	State       string `json:"state"`
	Nonce       string `json:"nonce"`
	Verifier    string `json:"verifier"`
	RedirectURI string `json:"redirect_uri"`
	ReturnTo    string `json:"return_to,omitempty"`
	// CreatedAt is unix seconds.
	CreatedAt int64 `json:"created_at"`
}

PendingLogin is what to keep between the redirect to 9in and the callback, for about 15 minutes. It holds the PKCE verifier: store it server-side or encrypted, and delete it when the callback arrives. It marshals to JSON.

type ProcessStatus

type ProcessStatus string

ProcessStatus is the outcome of processing an event once.

const (
	// Processed: the first delivery, and the handler succeeded. Answer 2xx.
	Processed ProcessStatus = "processed"
	// Duplicate: already processed. Answer 2xx so 9in stops retrying.
	Duplicate ProcessStatus = "duplicate"
	// InProgress: another delivery of the same event is still running. Answer 409 so 9in
	// tries again later.
	InProgress ProcessStatus = "in_progress"
)

func ProcessEventOnce

func ProcessEventOnce(ctx context.Context, store Store, eventID string, handler func(context.Context) error) (ProcessStatus, error)

ProcessEventOnce runs handler at most once per event id with the default TTLs. See EventDeduplicator.Process.

status, err := nine.ProcessEventOnce(ctx, store, event.ID, func(ctx context.Context) error { return handle(ctx, event) })

type Store added in v0.2.0

type Store interface {
	// Get returns the value of key, and whether it exists and hasn't expired.
	Get(ctx context.Context, key string) (value string, ok bool, err error)
	// Set stores value under key for ttl.
	Set(ctx context.Context, key, value string, ttl time.Duration) error
	// Add stores value under key for ttl only if key is missing or expired, atomically,
	// and reports whether it stored it.
	Add(ctx context.Context, key, value string, ttl time.Duration) (bool, error)
	// Delete removes key.
	Delete(ctx context.Context, key string) error
}

Store is a small key-value store with expiry, for state the SDK shares across requests and, with a shared implementation, across processes: processed webhook ids (EventDeduplicator, WebhookHandler) and hybrid verification answers with their revocation markers (VerifierConfig.Store).

Keys are short ASCII strings and values are strings. Add must be atomic: store the value only when the key is missing or expired, and report whether it did (Redis SET NX PX, an SQL insert on a unique key, a conditional put). A store that drops keys early under memory pressure (Redis with an allkeys eviction policy) can let a webhook be handled twice, so use one that keeps keys until they expire.

MemoryStore is the implementation for one process.

type TokenSet

type TokenSet struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type,omitempty"`
	// ExpiresAt is when the access token expires.
	ExpiresAt time.Time `json:"expires_at"`
	// RefreshToken comes with the offline_access scope. 9in rotates it: keep the new one
	// after every refresh.
	RefreshToken string `json:"refresh_token,omitempty"`
	IDToken      string `json:"id_token,omitempty"`
	Scope        string `json:"scope,omitempty"`
	// Claims are the verified ID token's claims (sub, email, name, amr, sid…), nil
	// without an ID token.
	Claims Claims `json:"claims,omitempty"`
	// ReturnTo is the path to send the user to after sign-in, from the pending login
	// (only a same-site path is kept).
	ReturnTo string `json:"return_to,omitempty"`
}

TokenSet is what a sign-in, a refresh or a client-credentials request returns. It marshals to JSON (snake_case keys), so you can keep it in a server-side session.

func (*TokenSet) Expired

func (t *TokenSet) Expired(leeway time.Duration) bool

Expired reports whether the access token has expired, or will within leeway.

type User

type User struct {
	// Subject is the user's 9in id (the sub claim).
	Subject       string `json:"sub"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Name          string `json:"name,omitempty"`
	GivenName     string `json:"given_name,omitempty"`
	FamilyName    string `json:"family_name,omitempty"`
	Picture       string `json:"picture,omitempty"`
	PhoneNumber   string `json:"phone_number,omitempty"`
	Locale        string `json:"locale,omitempty"`
	// Claims are all of the user's claims (profile, custom fields, amr, auth_time…).
	Claims Claims `json:"claims"`
}

User is the signed-in user of a WebApp, from the ID token.

func UserFrom

func UserFrom(ctx context.Context) *User

UserFrom returns the signed-in user WebApp.Middleware or WebApp.RequireUser put in the request context, or nil.

type UserChanges

type UserChanges map[string]any

UserChanges are the fields UpdateUser changes, with the API's names ("name", "phone_number", "email_verified", "metadata", "blocked", "password"…). A nil value clears a field. Metadata is replaced as a whole: read, merge, then send.

type UserDetail

type UserDetail struct {
	User        ManagedUser       `json:"user"`
	Identities  []ManagedIdentity `json:"identities"`
	Sessions    []ManagedSession  `json:"sessions"`
	HasPassword bool              `json:"has_password"`
	MFA         MFAState          `json:"mfa"`
}

UserDetail is what GetUser returns: the user with their identities, active sessions and two-factor state.

type UserList

type UserList struct {
	Users      []ManagedUser `json:"users"`
	NextCursor string        `json:"next_cursor"`
	Total      int           `json:"total"`
}

UserList is a page of users. Pass NextCursor back as the cursor for the next page; it is empty on the last page.

type UserQuery

type UserQuery struct {
	ID         string
	Identifier *Identifier
}

UserQuery is what 9in looks a user up by: ID (your own user id) or Identifier.

type Verifier

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

Verifier verifies 9in access tokens for your API. Create one at startup and share it: it caches your tenant's keys (and, in hybrid mode, 9in's answers), and is safe for concurrent use.

Every algorithm of 9in's key library is accepted: RS256/384/512, PS256/384/512, ES256, ES384 and EdDSA against the tenant's JWKS, and HS256/384/512 with the API's shared secret. Tokens must be access tokens (typ at+jwt); when the JWKS key names an algorithm, the token must use exactly that one, and the key type must fit it. The issuer, expiry (exp, nbf), audience and required scopes are checked. Keys are cached for ten minutes and fetched again once when a token names an unknown key.

func NewVerifier

func NewVerifier(cfg VerifierConfig) (*Verifier, error)

NewVerifier returns a Verifier. It fails for a malformed or insecure issuer, an unknown mode, or hybrid/introspect mode without client credentials.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	verifier, err := nine.NewVerifier(nine.VerifierConfig{
		Issuer:   "https://acme.9in.io",
		Audience: "https://api.acme.com",
	})
	if err != nil {
		log.Fatal(err)
	}
	claims, err := verifier.Verify(context.Background(), "eyJhbGciOi…", "orders:read")
	switch {
	case errors.Is(err, nine.ErrInsufficientScope): // 403
	case errors.Is(err, nine.ErrInvalidToken): // 401
	case err != nil: // 9in unreachable
	default:
		fmt.Println(claims.Subject(), claims.Scopes())
	}
}
Example (Hybrid)

Hybrid verification: revocations take effect as soon as the webhook arrives.

package main

import (
	"log"
	"net/http"
	"os"
	"time"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	verifier, err := nine.NewVerifier(nine.VerifierConfig{
		Issuer:       "https://acme.9in.io",
		Audience:     "https://api.acme.com",
		ClientID:     os.Getenv("NINE_CLIENT_ID"), // a confidential application:
		ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
		// Mode: nine.ModeHybrid is the default with client credentials.
		CacheTTL: 5 * time.Minute,
	})
	if err != nil {
		log.Fatal(err)
	}
	mux := http.NewServeMux()
	mux.Handle("/api/orders", nine.RequireAuth(verifier, "orders:read")(http.HandlerFunc(listOrders)))
	// Subscribed to token.revoked, session.revoked and user.* events.
	mux.Handle("/nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
		Secret:   os.Getenv("NINE_WEBHOOK_SECRET"),
		Verifier: verifier,
	}))
}

func listOrders(w http.ResponseWriter, r *http.Request) {}

func (*Verifier) Clear

func (v *Verifier) Clear(ctx context.Context) error

Clear forgets every cached hybrid answer (in every process, with a shared Store).

func (*Verifier) HandleEvent

func (v *Verifier) HandleEvent(ctx context.Context, event *WebhookEvent) (int, error)

HandleEvent drops the cached hybrid answers a webhook event makes stale: token.revoked (an access token) by jti, session.revoked by sid, and user.sessions_revoked, user.deleted, user.updated and user.password_changed by user. Subscribe your webhook endpoint to those events and pass every verified event here (WebhookConfig.Verifier does it for you).

It returns how many answers it dropped from the in-memory cache, or, with a shared VerifierConfig.Store, 1 when it wrote a revocation marker (the answers it covers can't be counted). An error means the shared store couldn't be written: answer the webhook with a 5xx so 9in delivers it again.

func (*Verifier) Issuer

func (v *Verifier) Issuer() string

Issuer is the normalised issuer.

func (*Verifier) Mode

func (v *Verifier) Mode() Mode

Mode is the verification mode in use.

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, token string, scopes ...string) (Claims, error)

Verify verifies an access token (or an Authorization header value, "Bearer …") and returns its claims. Each scope argument may hold several space-separated scopes; all must be granted.

It fails with invalid_token (Status 401) for a bad token and insufficient_scope (403) when a scope is missing. Other errors (9in unreachable, introspection refused) are your server's problem, not the caller's.

func (*Verifier) VerifyIDToken

func (v *Verifier) VerifyIDToken(ctx context.Context, idToken, clientID, nonce string) (Claims, error)

VerifyIDToken verifies an ID token issued to clientID: the signature (asymmetric keys only: 9in signs ID tokens with the tenant's default key), issuer, audience (and azp when there are several audiences), expiry, the nonce when expected is not empty, and that it is not an access token. It fails with invalid_id_token.

type VerifierConfig

type VerifierConfig struct {
	// Issuer is your tenant's issuer, exactly as in the tokens' iss claim, e.g.
	// https://acme.9in.io or your custom login domain.
	Issuer string
	// Audience is your API's identifier: tokens must have it in aud. Leave empty to
	// accept any audience (not recommended).
	Audience string
	// Audiences are more API identifiers to accept, besides Audience.
	Audiences []string
	// Secret is your API's shared secret, for APIs that sign with an HMAC key
	// (HS256/384/512) from the console's key library. JWKS keys need nothing.
	Secret string

	// Mode defaults to ModeHybrid when ClientID and ClientSecret are set, else ModeLocal.
	Mode Mode
	// ClientID and ClientSecret are a confidential application of the tenant, used for
	// introspection (ModeHybrid, ModeIntrospect and opaque tokens).
	ClientID     string
	ClientSecret string
	// CacheTTL is the longest a hybrid answer is trusted without news from 9in.
	// Default 5 minutes. An answer is never kept past the token's expiry.
	CacheTTL time.Duration
	// Store keeps hybrid answers in a store shared by all your processes (Redis, your
	// database), so a revocation webhook received by one of them reaches them all: the
	// process that gets the event writes a small revocation marker, which every process
	// checks before trusting a cached answer. The same Store can serve [WebhookHandler].
	// Default: in memory, per process (then every process must get the webhooks).
	Store Store
	// CacheSize is the most answers the default in-memory cache keeps (default 10 000;
	// the least recently used go first). Not used with Store.
	CacheSize int

	// Leeway is the clock skew allowed for exp and nbf. Default 30 seconds.
	Leeway time.Duration
	// HTTPClient is used for discovery, JWKS and introspection. Default: a client with a
	// 10-second timeout. Redirects are never followed.
	HTTPClient *http.Client
	// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
	AllowInsecureIssuer bool
}

VerifierConfig configures a Verifier.

func VerifierConfigFromEnv

func VerifierConfigFromEnv() VerifierConfig

VerifierConfigFromEnv returns a VerifierConfig from NINE_ISSUER, NINE_AUDIENCE, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_API_SECRET and NINE_ALLOW_INSECURE_ISSUER. With a client ID and secret the verifier runs in hybrid mode.

type WebApp

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

WebApp is sign-in for a server-rendered Go web app, ready to mount: the /nine/login, /nine/signup, /nine/callback and /nine/logout routes, an encrypted cookie session (AES-256-GCM; no server-side storage), token refresh with rotation, and [RequireUser] middleware. It works with any router that speaks http.Handler.

app, err := nine.NewWebApp(nine.WebAppConfigFromEnv())
mux.Handle("/nine/", app)
mux.Handle("/dashboard", app.RequireUser(dashboard))

In a handler, UserFrom returns the signed-in user and WebApp.AccessToken a valid access token for your API. Safe for concurrent use.

func NewWebApp

func NewWebApp(cfg WebAppConfig) (*WebApp, error)

NewWebApp returns a WebApp. It fails when the issuer, client ID or secret is missing or invalid.

Example
package main

import (
	"log"
	"net/http"
	"os"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	app, err := nine.NewWebApp(nine.WebAppConfig{
		Issuer:       "https://acme.9in.io",
		ClientID:     "app_7f3k2m9q",
		ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
		Secret:       os.Getenv("NINE_SECRET"), // encrypts the session cookie
		BaseURL:      "https://app.acme.com",   // callback: https://app.acme.com/nine/callback
		Audience:     "https://api.acme.com",   // access tokens for your API
	})
	if err != nil {
		log.Fatal(err)
	}
	http.Handle("/nine/", app)
	http.Handle("/orders", app.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token, err := app.AccessToken(w, r) // refreshed (and rotated) when needed
		if err != nil {
			http.Redirect(w, r, "/nine/login", http.StatusFound)
			return
		}
		req, _ := http.NewRequestWithContext(r.Context(), "GET", "https://api.acme.com/orders", nil)
		req.Header.Set("Authorization", "Bearer "+token)
		// … call your API
	})))
}

func (*WebApp) AccessToken

func (a *WebApp) AccessToken(w http.ResponseWriter, r *http.Request) (string, error)

AccessToken returns a valid access token for the signed-in user (for your API, with Audience set), refreshing it when it expires within RefreshLeeway and saving the rotated refresh token in the cookie. Call it before writing the response body, so the cookie can still be set. It fails with login_required (401) when there is no session or it ended.

func (*WebApp) Auth

func (a *WebApp) Auth() *WebAppAuth

Auth is the underlying WebAppAuth (refresh, revoke, userinfo, client credentials).

func (*WebApp) Callback

func (a *WebApp) Callback(w http.ResponseWriter, r *http.Request)

Callback finishes a sign-in (the /nine/callback route): it checks the callback against the sign-in cookie, starts the session and redirects to return_to.

func (*WebApp) Login

func (a *WebApp) Login(w http.ResponseWriter, r *http.Request)

Login starts a sign-in (the /nine/login route). Query parameters: return_to (a path on your site), screen=signup, prompt, login_hint, locale.

func (*WebApp) Logout

func (a *WebApp) Logout(w http.ResponseWriter, r *http.Request)

Logout signs the user out (the /nine/logout route, GET or POST): it clears the session, revokes the refresh token and sends the browser to 9in's end-session URL, which comes back to return_to (a path) or AfterSignOutPath. local=1 skips ending the 9in session.

func (*WebApp) Middleware

func (a *WebApp) Middleware(next http.Handler) http.Handler

Middleware reads the session for every request it wraps: UserFrom returns the user (nil when signed out), and the access token is refreshed before it expires. Signed-out visitors go through; use WebApp.RequireUser to keep them out.

func (*WebApp) RequireUser

func (a *WebApp) RequireUser(next http.Handler) http.Handler

RequireUser is WebApp.Middleware for pages that need a signed-in user. Signed-out visitors are sent to the sign-in page and brought back afterwards; requests that aren't page navigations (fetch, API calls) get 401 JSON instead.

func (*WebApp) ServeHTTP

func (a *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the sign-in routes under BasePath: GET login, GET signup, GET callback, and GET or POST logout. Anything else is 404.

func (*WebApp) Signup

func (a *WebApp) Signup(w http.ResponseWriter, r *http.Request)

Signup opens the sign-up form (the /nine/signup route). It takes the same query parameters as Login.

func (*WebApp) User

func (a *WebApp) User(r *http.Request) *User

User returns the signed-in user of the request (from the context when the middleware ran, else from the session cookie), or nil.

type WebAppAuth

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

WebAppAuth signs users in to a server-side web app: the authorization code flow with PKCE (S256), state and nonce, the RFC 9207 iss check, and the ID token verified against your tenant's keys. It also refreshes tokens (9in rotates refresh tokens), revokes them, builds the logout URL, reads userinfo and gets client-credentials tokens.

You keep the PendingLogin between WebAppAuth.CreateLogin and WebAppAuth.HandleCallback (in the user's session, or an encrypted cookie) and the TokenSet afterwards. WebApp does all of that for you. Safe for concurrent use.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	auth, err := nine.NewWebAppAuth(nine.WebAppAuthConfig{
		Issuer:       "https://acme.9in.io",
		ClientID:     "app_7f3k2m9q",
		ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
		RedirectURI:  "https://app.acme.com/nine/callback",
	})
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	// /nine/login: keep login.Pending (server-side session, or encrypted) and redirect.
	login, err := auth.CreateLogin(ctx, nine.LoginOptions{ReturnTo: "/dashboard"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("redirect to", login.URL)

	// /nine/callback: checks state, iss and PKCE, and verifies the ID token.
	var r *http.Request // the callback request
	tokens, err := auth.HandleCallback(ctx, r.URL.Query(), login.Pending)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(tokens.Claims.Subject(), tokens.Claims.String("email"), tokens.ReturnTo)

	// Later: refresh before expiry and keep the result (9in rotates refresh tokens).
	tokens, err = auth.EnsureFresh(ctx, tokens, time.Minute)
	if err != nil {
		log.Fatal(err)
	}
	_ = tokens
}

func NewWebAppAuth

func NewWebAppAuth(cfg WebAppAuthConfig) (*WebAppAuth, error)

NewWebAppAuth returns a WebAppAuth. It fails when the issuer or client ID is missing, or the issuer is malformed or not https.

func (*WebAppAuth) ClientCredentials

func (a *WebAppAuth) ClientCredentials(ctx context.Context, opts ClientCredentialsOptions) (*TokenSet, error)

ClientCredentials gets a token for the application itself (no user), for your own API (opts.Audience) or the Management API. Confidential applications only. For a cached, self-refreshing token use ClientCredentials instead.

func (*WebAppAuth) ClientID

func (a *WebAppAuth) ClientID() string

ClientID is the application's client ID.

func (*WebAppAuth) CreateLogin

func (a *WebAppAuth) CreateLogin(ctx context.Context, opts LoginOptions) (*Login, error)

CreateLogin starts a sign-in: it returns the URL of your tenant's hosted sign-in page and the PendingLogin to keep until the callback.

func (*WebAppAuth) Discovery

func (a *WebAppAuth) Discovery(ctx context.Context) (*Discovery, error)

Discovery returns your tenant's discovery document (cached).

func (*WebAppAuth) EnsureFresh

func (a *WebAppAuth) EnsureFresh(ctx context.Context, tokens *TokenSet, leeway time.Duration) (*TokenSet, error)

EnsureFresh returns tokens unchanged (the same pointer) while the access token is valid for at least leeway, and refreshed tokens otherwise (keeping the ID token, claims and ReturnTo when the refresh doesn't replace them). Save the result.

func (*WebAppAuth) HandleCallback

func (a *WebAppAuth) HandleCallback(ctx context.Context, query url.Values, pending *PendingLogin) (*TokenSet, error)

HandleCallback finishes a sign-in on your callback URL. query is the callback's query (r.URL.Query()), pending what CreateLogin returned. It checks the error parameter, the pending login's age (15 minutes), the state (in constant time, and only once), the iss parameter (RFC 9207), exchanges the code with the PKCE verifier and verifies the ID token (signature, issuer, audience, expiry, nonce).

Errors: the OAuth error from 9in (access_denied when the user cancelled, login_required for prompt=none…), invalid_state, invalid_issuer, missing_code, invalid_grant and invalid_id_token.

func (*WebAppAuth) Issuer

func (a *WebAppAuth) Issuer() string

Issuer is the normalised issuer.

func (*WebAppAuth) LogoutURL

func (a *WebAppAuth) LogoutURL(ctx context.Context, opts LogoutOptions) (string, error)

LogoutURL is the URL that ends the session at 9in (RP-initiated logout) and returns to opts.PostLogoutRedirectURI, which must be an allowed logout URL of the application.

func (*WebAppAuth) Refresh

func (a *WebAppAuth) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)

Refresh exchanges a refresh token for new tokens. 9in rotates refresh tokens: keep the RefreshToken of the result (the old one is kept when 9in sends none). When 9in sends a new ID token it is verified and its claims are in Claims.

func (*WebAppAuth) Revoke

func (a *WebAppAuth) Revoke(ctx context.Context, token, hint string) error

Revoke revokes a refresh token (and its whole rotation family; hint "refresh_token", the default) or an access token (hint "access_token"). 9in answers success for unknown tokens, so an error is a real failure such as invalid_client.

func (*WebAppAuth) UserInfo

func (a *WebAppAuth) UserInfo(ctx context.Context, accessToken string) (Claims, error)

UserInfo returns the user's current claims from the userinfo endpoint. A revoked or expired token gets invalid_token.

func (*WebAppAuth) VerifyIDToken

func (a *WebAppAuth) VerifyIDToken(ctx context.Context, idToken, nonce string) (Claims, error)

VerifyIDToken verifies an ID token issued to this application (nonce: the one sent with the sign-in, or "" to skip that check).

type WebAppAuthConfig

type WebAppAuthConfig struct {
	// Issuer is your tenant's issuer, e.g. https://acme.9in.io or your custom login domain.
	Issuer string
	// ClientID is the application's client ID.
	ClientID string
	// ClientSecret is set for confidential applications (sent with HTTP Basic,
	// client_secret_basic). Leave it empty for public ones, which rely on PKCE alone.
	ClientSecret string
	// RedirectURI is your callback URL, as registered on the application. It can also be
	// given per sign-in ([LoginOptions].RedirectURI).
	RedirectURI string
	// Scopes default to [DefaultScopes].
	Scopes []string
	// Audience is an API identifier, to get access tokens for that API.
	Audience string
	// Leeway is the clock skew allowed when checking ID tokens. Default 30 seconds.
	Leeway time.Duration
	// HTTPClient is used for every call to 9in. Default: a client with a 10-second
	// timeout. Redirects are never followed.
	HTTPClient *http.Client
	// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
	AllowInsecureIssuer bool
}

WebAppAuthConfig configures a WebAppAuth.

func WebAppAuthConfigFromEnv

func WebAppAuthConfigFromEnv() WebAppAuthConfig

WebAppAuthConfigFromEnv returns a WebAppAuthConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI, NINE_AUDIENCE and NINE_ALLOW_INSECURE_ISSUER.

type WebAppConfig

type WebAppConfig struct {
	// Issuer is your tenant's issuer, e.g. https://acme.9in.io (NINE_ISSUER).
	Issuer string
	// ClientID is the application's client ID (NINE_CLIENT_ID).
	ClientID string
	// ClientSecret is set for a confidential application (NINE_CLIENT_SECRET). Leave it
	// empty for a public one.
	ClientSecret string
	// Secret encrypts the session and sign-in cookies (NINE_SECRET): 32 characters or
	// more, e.g. from `openssl rand -base64 32`.
	Secret string
	// Secrets are older secrets that still decrypt cookies while you rotate.
	Secrets []string
	// BaseURL is your app's URL, e.g. https://app.acme.com (NINE_BASE_URL). The callback
	// URL is BaseURL + BasePath + "/callback". Default: the scheme and host of each
	// request; set it in production, especially behind a proxy.
	BaseURL string
	// BasePath is where the routes are mounted. Default "/nine": /nine/login,
	// /nine/signup, /nine/callback and /nine/logout. "/" mounts them at the root.
	BasePath string
	// Scopes default to [DefaultScopes] (offline_access gives a refresh token).
	Scopes []string
	// Audience is an API identifier, to get access tokens for that API (NINE_AUDIENCE).
	Audience string
	// CookieName is the session cookie's name. Default "nine_session".
	CookieName string
	// SessionMaxAge is how long a session lasts without being used. Default 30 days;
	// each token refresh starts it again.
	SessionMaxAge time.Duration
	// RefreshLeeway is how long before expiry the access token is refreshed. Default 60 seconds.
	RefreshLeeway time.Duration
	// AfterSignInPath is where users land after sign-in when no return_to was given.
	// Default "/".
	AfterSignInPath string
	// AfterSignOutPath is where users land after sign-out. BaseURL + this path must be
	// an allowed logout URL of the application. Default "/".
	AfterSignOutPath string
	// OnError writes the answer for a failed sign-in (access_denied when the user
	// cancels, say) or 9in being unreachable. Default: a plain-text error page.
	OnError func(w http.ResponseWriter, r *http.Request, err error)
	// HTTPClient is used for every call to 9in. Default: a client with a 10-second timeout.
	HTTPClient *http.Client
	// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
	AllowInsecureIssuer bool
}

WebAppConfig configures a WebApp.

func WebAppConfigFromEnv

func WebAppConfigFromEnv() WebAppConfig

WebAppConfigFromEnv returns a WebAppConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_SECRET (comma-separated to rotate: the first encrypts), NINE_BASE_URL, NINE_AUDIENCE and NINE_ALLOW_INSECURE_ISSUER.

type WebhookConfig

type WebhookConfig struct {
	// Secret is the endpoint's signing secret (NINE_WEBHOOK_SECRET).
	Secret string
	// Secrets are more secrets accepted while you rotate.
	Secrets []string
	// Handle is called once per event (after verification and de-duplication). Return
	// an error to have 9in retry the delivery later.
	Handle func(ctx context.Context, event *WebhookEvent) error
	// Store remembers processed event ids so each event is handled once. Default: in
	// memory (one process). With several instances, use a shared store (the same one
	// can serve the Verifier).
	Store Store
	// TTL is how long processed ids are remembered. Default 3 days.
	TTL time.Duration
	// Verifier is a hybrid verifier to keep current: every verified event goes to its
	// HandleEvent, so token.revoked, session.revoked and user.* evict cached answers.
	// When that fails (its shared Store is down), the delivery gets a 500 and 9in retries.
	Verifier *Verifier
	// Path is the path 9in posts to, when a proxy rewrites it before it reaches you.
	// Default: the request path as received.
	Path string
	// Tolerance is the signature timestamp tolerance. Default 5 minutes.
	Tolerance time.Duration
	// OnError is told about a failed Handle (the delivery gets a 500 and 9in retries) and
	// about store failures. Optional.
	OnError func(r *http.Request, err error)
}

WebhookConfig configures WebhookHandler.

type WebhookEvent

type WebhookEvent struct {
	ID        string    `json:"id"`
	EventType string    `json:"event_type"`
	CreatedAt time.Time `json:"created_at"`
	// Tenant is the tenant id (tnt_…).
	Tenant string `json:"tenant"`
	// Environment is "production" or "sandbox".
	Environment string         `json:"environment"`
	Data        map[string]any `json:"data"`
}

WebhookEvent is a webhook from 9in. Data carries the event's details plus "user", the user the event is about (the Management API user object, or nil when there is none; for user.deleted, the user as it was just before the deletion). ID is the same on every retry and redelivery.

func VerifyWebhook

func VerifyWebhook(secrets []string, body []byte, signature, path string) (*WebhookEvent, error)

VerifyWebhook checks a webhook's 9in-signature header against the raw body and the path 9in posted to (r.URL.Path, or what it was before a proxy rewrote it), with any of secrets (several while you rotate), and returns the event. It fails with invalid_signature (401), or invalid_payload (400) when the body isn't an event.

Example
package main

import (
	"context"
	"net/http"
	"os"

	nine "github.com/9in-io/go-sdk"
)

func main() {
	http.HandleFunc("POST /nine/webhook", func(w http.ResponseWriter, r *http.Request) {
		event, err := nine.VerifyWebhookRequest(r, os.Getenv("NINE_WEBHOOK_SECRET"))
		if err != nil {
			http.Error(w, "invalid signature", http.StatusUnauthorized)
			return
		}
		status, err := nine.ProcessEventOnce(r.Context(), store, event.ID, func(ctx context.Context) error {
			return handle(ctx, event)
		})
		switch {
		case status == nine.InProgress:
			w.WriteHeader(http.StatusConflict) // 9in retries later
		case err != nil:
			w.WriteHeader(http.StatusInternalServerError) // released: 9in retries
		default:
			w.WriteHeader(http.StatusNoContent)
		}
	})
}

var store = nine.NewMemoryStore()

func handle(context.Context, *nine.WebhookEvent) error { return nil }

func VerifyWebhookRequest

func VerifyWebhookRequest(r *http.Request, secrets ...string) (*WebhookEvent, error)

VerifyWebhookRequest reads and verifies a webhook request (POST, signature over the raw body and the request path as sent). It consumes r.Body.

func (*WebhookEvent) User

func (e *WebhookEvent) User() (*ManagedUser, error)

User decodes data.user into a ManagedUser; nil when the event is about no user.

func (*WebhookEvent) UserID

func (e *WebhookEvent) UserID() string

UserID is the id of the user the event is about (data.user.id), or "".

Directories

Path Synopsis
examples
adapter command
Command adapter keeps users in your own database: it serves the adapter protocol endpoints 9in calls (…/authenticate, …/user, …/event) over an in-memory user list.
Command adapter keeps users in your own database: it serves the adapter protocol endpoints 9in calls (…/authenticate, …/user, …/event) over an in-memory user list.
api command
Command api is an API protected with 9in access tokens, with a webhook endpoint that keeps hybrid verification current.
Command api is an API protected with 9in access tokens, with a webhook endpoint that keeps hybrid verification current.
device command
Command device signs in from a terminal with the device flow (RFC 8628).
Command device signs in from a terminal with the device flow (RFC 8628).
webapp command
Command webapp is a server-rendered web app that signs users in with 9in.
Command webapp is a server-rendered web app that signs users in with 9in.

Jump to

Keyboard shortcuts

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