wocha

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

wocha-go

Go SDK for the Wocha authentication and authorisation platform — Management API client and JWT resource server middleware.

Works with Wocha Cloud and self-hosted installations. Standard library only — no external HTTP dependencies.

Installation

go get github.com/Elementary-Digital/wocha-go

Requires Go 1.21 or later.

Quick start

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Elementary-Digital/wocha-go"
)

func main() {
	client, err := wocha.NewClient(
		wocha.WithAPIKey(os.Getenv("WOCHA_API_KEY")),
		wocha.WithTenant("acme"),
	)
	if err != nil {
		log.Fatal(err)
	}

	users, err := client.Users.List(context.Background(), &wocha.UserListParams{
		PageSize: 25,
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, u := range users.Data {
		fmt.Println(u.Email)
	}
}

Configuration

Tenant vs base URL

Use WithTenant for Wocha Cloud — the SDK resolves https://{tenant}.api.wocha.ai/v1:

wocha.NewClient(
	wocha.WithTenant("acme"),
	wocha.WithAPIKey("wocha_mgmt_..."),
)

Use WithBaseURL for self-hosted deployments:

wocha.NewClient(
	wocha.WithBaseURL("https://your-domain.com/v1"),
	wocha.WithAPIKey("wocha_mgmt_..."),
	wocha.WithTenantHeader("tenant-uuid"), // if tenant is not in the URL
)

Environment variables WOCHA_API_KEY and WOCHA_TENANT are used as fallbacks when options are omitted.

Options
Option Description
WithAPIKey Management API key (wocha_mgmt_...) or OAuth access token
WithTenant Tenant slug for Wocha Cloud
WithBaseURL Explicit API base URL
WithHTTPClient Custom *http.Client
WithTimeout Per-request timeout (default: 10s)
WithMaxRetries Retries on 429/5xx (default: 3)
WithTenantHeader X-Tenant-ID for self-hosted setups

Resources

The client exposes resource services matching the Customer API:

Service Example
Users client.Users.Get(ctx, "usr_abc")
Sessions client.Sessions.RevokeAll(ctx, "usr_abc")
Organisations client.Organisations.Create(ctx, params)
Permissions client.Permissions.Check(ctx, params)
Applications client.Applications.RotateSecret(ctx, id)
Products client.Products.ListScopes(ctx)
Webhooks client.Webhooks.Create(ctx, params)
Billing client.Billing.CreatePortalSession(ctx)
Branding client.Branding.GetTheme(ctx)
Logs client.Logs.ListAuthLogs(ctx, filter)
Connections client.Connections.ListSocial(ctx)
Actions client.Actions.Deploy(ctx, id)
APIKeys client.APIKeys.Create(ctx, params)
Permission check
resp, err := client.Permissions.Check(ctx, &wocha.PermissionCheckParams{
	UserID:       "user_123",
	Permission:   "read",
	ResourceType: "document",
	ResourceID:   "doc_456",
})
if resp.Allowed {
	// grant access
}
Idempotency keys

Attach an idempotency key to mutating requests via context:

ctx := wocha.WithIdempotencyKey(context.Background(), "my-unique-key")
user, err := client.Users.Create(ctx, params)
Pagination

List endpoints return cursor-based pages. Fetch all items with ListAll:

users, err := client.Users.ListAll(ctx, &wocha.UserListParams{PageSize: 100})

JWT validation (resource server)

Validate Wocha access tokens in your Go API using the JWKS endpoint:

package main

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

	wocha "github.com/Elementary-Digital/wocha-go"
)

func main() {
	validator, err := wocha.NewJWTValidator(wocha.JWTValidatorConfig{
		Issuer:   os.Getenv("WOCHA_ISSUER"),
		Audience: os.Getenv("WOCHA_AUDIENCE"), // optional
	})
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/api/protected", func(w http.ResponseWriter, r *http.Request) {
		claims := wocha.ClaimsFromContext(r.Context())
		fmt.Fprintf(w, `{"user": "%s"}`, claims.Subject)
	})

	// Wrap your router with the JWT middleware
	http.ListenAndServe(":8080", validator.Middleware(mux))
}
Scope checks

Use RequireScope to enforce OAuth scopes on specific routes:

protected := wocha.RequireScope("myapp:write")(myHandler)
Claims

ClaimsFromContext returns an *AccessTokenClaims with these fields:

Field Type Description
Subject string User ID
ClientID string OAuth client ID
Scope string Space-separated scopes
OrgID string Active organisation
TenantID string Wocha tenant
OrgIDs []string All user organisations
Ext map[string]interface{} Custom claims

See the Resource server guide for advanced patterns (tiered validation, introspection, DPoP).

Error handling

API errors implement *wocha.APIError and can be inspected with errors.As:

user, err := client.Users.Get(ctx, "nonexistent")
if err != nil {
	var apiErr *wocha.APIError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.Code)      // "not_found"
		fmt.Println(apiErr.RequestID) // "req_abc123"
	}
}

Typed wrappers are available for common status codes: AuthenticationError, PermissionError, NotFoundError, ValidationError, RateLimitError, and ServerError.

Webhook verification

Import the webhook subpackage to verify incoming webhook payloads:

import "github.com/Elementary-Digital/wocha-go/webhook"

event, err := webhook.Verify(payload, r.Header.Get("X-Wocha-Signature"), secret)
if err != nil {
	http.Error(w, "invalid signature", http.StatusUnauthorized)
	return
}

switch event.EventType {
case "user.created":
	// handle event
}

License

Apache 2.0 — see LICENSE.

Documentation

Overview

Webhook signature verification is provided by the webhook subpackage.

import "github.com/Elementary-Digital/wocha-go/webhook"

See webhook.Verify for signature validation and event parsing.

Package wocha provides a Go client for the Wocha auth platform Management API.

Create a client with functional options:

client, err := wocha.NewClient(
    wocha.WithAPIKey("wocha_mgmt_..."),
    wocha.WithTenant("acme"),
)

Webhook signature verification lives in the webhook subpackage:

import "github.com/Elementary-Digital/wocha-go/webhook"

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsAPIError

func IsAPIError(err error) bool

IsAPIError reports whether err is an APIError (or a typed wrapper).

func Paginate

func Paginate[T any](ctx context.Context, listFn func(context.Context, *ListParams) (*PaginatedResponse[T], error), params *ListParams) ([]T, error)

Paginate fetches all pages from a cursor-paginated list endpoint.

func RequireScope

func RequireScope(scope string) func(http.Handler) http.Handler

RequireScope returns a middleware that rejects requests without the specified OAuth scope. Must be used after Middleware.

func WithIdempotencyKey

func WithIdempotencyKey(ctx context.Context, key string) context.Context

WithIdempotencyKey attaches an idempotency key to ctx for the next mutating request.

Types

type APIError

type APIError struct {
	Code        string
	Message     string
	StatusCode  int
	RequestID   string
	DocsURL     string
	Category    ErrorCategory
	FieldErrors map[string][]string
	RetryAfter  *int
}

APIError is the base error type for Wocha API failures.

func (*APIError) Error

func (e *APIError) Error() string

type APIKey

type APIKey = ApiKey

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type APIKeyCreateParams

type APIKeyCreateParams = CreateApiKeyRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type APIKeyCreateResponse

type APIKeyCreateResponse = ApiKeyWithSecret

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type APIKeyRotateResponse

type APIKeyRotateResponse = RotateApiKeyResponse

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type APIKeyUpdateParams

type APIKeyUpdateParams = UpdateApiKeyRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type APIKeysService

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

APIKeysService manages Management API keys.

func (*APIKeysService) Create

Create creates a new Management API key.

func (*APIKeysService) Delete

func (s *APIKeysService) Delete(ctx context.Context, id string) error

Delete revokes an API key.

func (*APIKeysService) Get

func (s *APIKeysService) Get(ctx context.Context, id string) (*APIKey, error)

Get retrieves an API key by ID.

func (*APIKeysService) List

List returns a paginated list of API keys.

func (*APIKeysService) ListAll

func (s *APIKeysService) ListAll(ctx context.Context, params *ListParams) ([]APIKey, error)

ListAll fetches all API keys across pages.

func (*APIKeysService) Rotate

Rotate rotates an API key and returns the new secret.

func (*APIKeysService) Update

func (s *APIKeysService) Update(ctx context.Context, id string, params *APIKeyUpdateParams) (*APIKey, error)

Update updates an API key.

type AccessTokenClaims

type AccessTokenClaims struct {
	Subject  string                 `json:"sub"`
	ClientID string                 `json:"client_id"`
	Scope    string                 `json:"scope"`
	Issuer   string                 `json:"iss"`
	Audience []string               `json:"aud"`
	Exp      int64                  `json:"exp"`
	Iat      int64                  `json:"iat"`
	Nbf      int64                  `json:"nbf"`
	OrgID    string                 `json:"org_id"`
	TenantID string                 `json:"tenant_id"`
	OrgIDs   []string               `json:"org_ids"`
	Ext      map[string]interface{} `json:"ext"`
}

AccessTokenClaims holds the verified claims from a Wocha access token.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) *AccessTokenClaims

ClaimsFromContext retrieves the validated AccessTokenClaims from the request context. Returns nil if the request was not authenticated.

func (*AccessTokenClaims) HasScope

func (c *AccessTokenClaims) HasScope(scope string) bool

HasScope returns true if the token includes the given OAuth scope.

type AccountMfaStatus

type AccountMfaStatus struct {
	BackupCodesRemaining int      `json:"backup_codes_remaining"`
	Enabled              bool     `json:"enabled"`
	Methods              []string `json:"methods"`
}

type AccountMfaStatusResponse

type AccountMfaStatusResponse struct {
	Data AccountMfaStatus `json:"data"`
}

type AccountOrganisation

type AccountOrganisation struct {
	DisplayName *string `json:"display_name,omitempty"`
	ID          string  `json:"id"`
	JoinedAt    string  `json:"joined_at"`
	Role        string  `json:"role"`
	Slug        string  `json:"slug"`
}

type AccountOrganisationListResponse

type AccountOrganisationListResponse struct {
	Data []AccountOrganisation `json:"data"`
}

type AccountPasskey

type AccountPasskey struct {
	CreatedAt   *string `json:"created_at,omitempty"`
	DisplayName string  `json:"display_name"`
	ID          string  `json:"id"`
	UpdatedAt   *string `json:"updated_at,omitempty"`
}

type AccountPasskeyListResponse

type AccountPasskeyListResponse struct {
	Data []AccountPasskey `json:"data"`
}

type AccountProfile

type AccountProfile struct {
	AvatarUrl   *string         `json:"avatar_url,omitempty"`
	CreatedAt   string          `json:"created_at"`
	DisplayName *string         `json:"display_name,omitempty"`
	Email       string          `json:"email"`
	ID          string          `json:"id"`
	Metadata    json.RawMessage `json:"metadata"`
	UpdatedAt   string          `json:"updated_at,omitempty"`
}

type AccountProfileResponse

type AccountProfileResponse struct {
	Data AccountProfile `json:"data"`
}

type AccountSession

type AccountSession struct {
	// User agent string
	Device     *string `json:"device,omitempty"`
	ExpiresAt  *string `json:"expires_at,omitempty"`
	ID         string  `json:"id"`
	IpAddress  *string `json:"ip_address,omitempty"`
	IsCurrent  bool    `json:"is_current"`
	LastActive *string `json:"last_active,omitempty"`
	Location   *string `json:"location,omitempty"`
}

type AccountSessionListResponse

type AccountSessionListResponse struct {
	Data []AccountSession `json:"data"`
}

type Action

type Action struct {
	// JavaScript source code
	Code           string          `json:"code"`
	CreatedAt      string          `json:"created_at"`
	Dependencies   []string        `json:"dependencies"`
	ID             string          `json:"id"`
	LastDeployedAt *string         `json:"last_deployed_at,omitempty"`
	LastExecution  json.RawMessage `json:"last_execution,omitempty"`
	Name           string          `json:"name"`
	// Execution order within the same trigger
	Order   int    `json:"order"`
	Runtime string `json:"runtime"`
	// Masked secret values
	Secrets   json.RawMessage `json:"secrets,omitempty"`
	Status    string          `json:"status"`
	TenantId  string          `json:"tenant_id"`
	TimeoutMs int             `json:"timeout_ms"`
	Trigger   string          `json:"trigger"`
	UpdatedAt string          `json:"updated_at"`
	Version   int             `json:"version,omitempty"`
}

type ActionCreateParams

type ActionCreateParams = CreateActionRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type ActionDeployment

type ActionDeployment struct {
	ActionId   string `json:"action_id"`
	DeployedAt string `json:"deployed_at,omitempty"`
	Error      string `json:"error,omitempty"`
	ID         string `json:"id"`
	Status     string `json:"status"`
	Version    int    `json:"version"`
}

type ActionExecutionLog

type ActionExecutionLog struct {
	ActionId     string          `json:"action_id"`
	CreatedAt    string          `json:"created_at"`
	DurationMs   int             `json:"duration_ms"`
	Error        *string         `json:"error,omitempty"`
	ID           string          `json:"id"`
	InputEvent   json.RawMessage `json:"input_event,omitempty"`
	IsTest       bool            `json:"is_test"`
	Logs         []string        `json:"logs"`
	OutputResult json.RawMessage `json:"output_result,omitempty"`
	Status       string          `json:"status"`
	Trigger      string          `json:"trigger"`
}

type ActionList

type ActionList struct {
	Data []Action `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type ActionLogList

type ActionLogList struct {
	Data []ActionExecutionLog `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type ActionTestResult

type ActionTestResult struct {
	DurationMs int      `json:"duration_ms,omitempty"`
	Error      string   `json:"error,omitempty"`
	Logs       []string `json:"logs,omitempty"`
	// Action return value (alias of result)
	Output json.RawMessage `json:"output,omitempty"`
	// Action return value
	Result  json.RawMessage `json:"result,omitempty"`
	Success bool            `json:"success"`
}

type ActionTriggerDefinition

type ActionTriggerDefinition struct {
	CanDeny     bool     `json:"can_deny"`
	CanModify   bool     `json:"can_modify"`
	Description string   `json:"description"`
	EventFields []string `json:"event_fields"`
	Label       string   `json:"label"`
	Trigger     string   `json:"trigger"`
}

type ActionTriggerList

type ActionTriggerList struct {
	Total    int                       `json:"total"`
	Triggers []ActionTriggerDefinition `json:"triggers"`
}

type ActionUpdateParams

type ActionUpdateParams = UpdateActionRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type ActionsService

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

ActionsService manages custom action hooks.

func (*ActionsService) Create

func (s *ActionsService) Create(ctx context.Context, params *ActionCreateParams) (*Action, error)

Create creates a new action.

func (*ActionsService) Delete

func (s *ActionsService) Delete(ctx context.Context, id string) error

Delete deletes an action.

func (*ActionsService) Deploy

func (s *ActionsService) Deploy(ctx context.Context, id string) (*ActionDeployment, error)

Deploy deploys an action.

func (*ActionsService) Get

func (s *ActionsService) Get(ctx context.Context, id string) (*Action, error)

Get retrieves an action by ID.

func (*ActionsService) List

List returns a paginated list of actions.

func (*ActionsService) ListAll

func (s *ActionsService) ListAll(ctx context.Context, params *ListParams) ([]Action, error)

ListAll fetches all actions across pages.

func (*ActionsService) Test

func (s *ActionsService) Test(ctx context.Context, id string, payload map[string]any) (*ActionTestResult, error)

Test runs an action in dry-run mode.

func (*ActionsService) Update

func (s *ActionsService) Update(ctx context.Context, id string, params *ActionUpdateParams) (*Action, error)

Update updates an action.

type ActiveSession

type ActiveSession struct {
	Aal             string `json:"aal,omitempty"`
	Active          bool   `json:"active,omitempty"`
	AuthenticatedAt string `json:"authenticated_at,omitempty"`
	ExpiresAt       string `json:"expires_at,omitempty"`
	ID              string `json:"id,omitempty"`
	IdentityId      string `json:"identity_id,omitempty"`
	// Active organisation context from identity metadata
	OrgID string `json:"org_id,omitempty"`
}

type ActiveSessionList

type ActiveSessionList struct {
	Data []ActiveSession `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type AddOrgMemberRequest

type AddOrgMemberRequest struct {
	IdentityId string `json:"identity_id"`
	Role       string `json:"role,omitempty"`
}

type ApiKey

type ApiKey struct {
	CreatedAt string  `json:"created_at"`
	ExpiresAt *string `json:"expires_at,omitempty"`
	ID        string  `json:"id"`
	// Allowed source IP addresses (empty = unrestricted)
	IpAllowlist []string `json:"ip_allowlist"`
	// First 8 characters of the key for identification
	KeyPrefix           string   `json:"key_prefix"`
	LastUsedAt          *string  `json:"last_used_at,omitempty"`
	Name                string   `json:"name"`
	RotatedFrom         *string  `json:"rotated_from,omitempty"`
	RotationGraceEndsAt *string  `json:"rotation_grace_ends_at,omitempty"`
	Scopes              []string `json:"scopes"`
	Status              string   `json:"status"`
}

type ApiKeyList

type ApiKeyList struct {
	Data []ApiKey `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type ApiKeyWithSecret

type ApiKeyWithSecret struct {
	CreatedAt string  `json:"created_at"`
	ExpiresAt *string `json:"expires_at,omitempty"`
	ID        string  `json:"id"`
	// Allowed source IP addresses (empty = unrestricted)
	IpAllowlist []string `json:"ip_allowlist"`
	// Full API key secret (shown once at creation)
	Key string `json:"key"`
	// First 8 characters of the key for identification
	KeyPrefix           string   `json:"key_prefix"`
	LastUsedAt          *string  `json:"last_used_at,omitempty"`
	Name                string   `json:"name"`
	RotatedFrom         *string  `json:"rotated_from,omitempty"`
	RotationGraceEndsAt *string  `json:"rotation_grace_ends_at,omitempty"`
	Scopes              []string `json:"scopes"`
	Status              string   `json:"status"`
}

type Application

type Application struct {
	ClientId   string   `json:"client_id"`
	ClientName string   `json:"client_name"`
	ClientUri  string   `json:"client_uri,omitempty"`
	CreatedAt  string   `json:"created_at,omitempty"`
	GrantTypes []string `json:"grant_types"`
	// Same as client_id (normalised)
	ID                      string   `json:"id"`
	RedirectUris            []string `json:"redirect_uris"`
	ResponseTypes           []string `json:"response_types"`
	Scope                   string   `json:"scope"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
}

type ApplicationCreateParams

type ApplicationCreateParams = CreateApplicationRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type ApplicationUpdateParams

type ApplicationUpdateParams = UpdateApplicationRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type ApplicationsService

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

ApplicationsService manages OAuth 2.0 applications.

func (*ApplicationsService) Create

Create creates a new OAuth application.

func (*ApplicationsService) Delete

func (s *ApplicationsService) Delete(ctx context.Context, id string) error

Delete deletes an application.

func (*ApplicationsService) Get

Get retrieves an application by ID.

func (*ApplicationsService) List

List returns a paginated list of applications.

func (*ApplicationsService) ListAll

func (s *ApplicationsService) ListAll(ctx context.Context, params *ListParams) ([]Application, error)

ListAll fetches all applications across pages.

func (*ApplicationsService) RotateSecret

func (s *ApplicationsService) RotateSecret(ctx context.Context, id string) (map[string]string, error)

RotateSecret rotates an application's client secret.

func (*ApplicationsService) Update

Update updates an application.

type AuditLogEntry

type AuditLogEntry struct {
	ID         string          `json:"id"`
	EventType  string          `json:"event_type"`
	ActorType  string          `json:"actor_type,omitempty"`
	ActorID    string          `json:"actor_id,omitempty"`
	TargetType string          `json:"target_type,omitempty"`
	TargetID   string          `json:"target_id,omitempty"`
	Outcome    string          `json:"outcome"`
	Metadata   json.RawMessage `json:"metadata,omitempty"`
	CreatedAt  string          `json:"created_at"`
}

AuditLogEntry is a management audit log record.

type AuthLogEntry

type AuthLogEntry struct {
	ID         string          `json:"id"`
	EventType  string          `json:"event_type"`
	IdentityID string          `json:"identity_id,omitempty"`
	IPAddress  string          `json:"ip_address,omitempty"`
	UserAgent  string          `json:"user_agent,omitempty"`
	Outcome    string          `json:"outcome"`
	Metadata   json.RawMessage `json:"metadata,omitempty"`
	CreatedAt  string          `json:"created_at"`
}

AuthLogEntry is an authentication log record.

type AuthenticationError

type AuthenticationError struct {
	*APIError
}

AuthenticationError indicates an HTTP 401 response.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

type BadRequestError

type BadRequestError struct {
	*APIError
}

BadRequestError indicates an HTTP 400 response that is not a validation error.

func (*BadRequestError) Error

func (e *BadRequestError) Error() string

func (*BadRequestError) Unwrap

func (e *BadRequestError) Unwrap() error

type BillingService

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

BillingService manages billing and subscription information.

func (*BillingService) CreatePortalSession

func (s *BillingService) CreatePortalSession(ctx context.Context) (*PortalSession, error)

CreatePortalSession creates a Stripe billing portal session.

func (*BillingService) GetSubscription

func (s *BillingService) GetSubscription(ctx context.Context) (*Subscription, error)

GetSubscription returns the tenant subscription details.

func (*BillingService) GetUsage

func (s *BillingService) GetUsage(ctx context.Context) (*UsageMetrics, error)

GetUsage returns current usage metrics and quotas.

type BillingSummary

type BillingSummary struct {
	PlanTier string `json:"plan_tier"`
	Status   string `json:"status"`
	TenantId string `json:"tenant_id"`
	// "configured" when a Vellon customer ID is set; null otherwise
	VellonCustomerId *string `json:"vellon_customer_id,omitempty"`
	// "configured" when a Vellon subscription ID is set; null otherwise
	VellonSubscriptionId *string `json:"vellon_subscription_id,omitempty"`
}

type Branding

type Branding struct {
	BackgroundColour string `json:"background_colour,omitempty"`
	CompanyName      string `json:"company_name,omitempty"`
	CustomCss        string `json:"custom_css,omitempty"`
	FaviconUrl       string `json:"favicon_url,omitempty"`
	FontFamily       string `json:"font_family,omitempty"`
	LogoUrl          string `json:"logo_url,omitempty"`
	PrimaryColour    string `json:"primary_colour,omitempty"`
}

type BrandingResponse

type BrandingResponse struct {
	Branding Branding `json:"branding,omitempty"`
	TenantId string   `json:"tenant_id,omitempty"`
}

type BrandingService

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

BrandingService manages branding, themes, and custom domains.

func (*BrandingService) GetDomain

func (s *BrandingService) GetDomain(ctx context.Context) (*CustomDomain, error)

GetDomain returns custom domain configuration.

func (*BrandingService) GetTheme

func (s *BrandingService) GetTheme(ctx context.Context) (*Theme, error)

GetTheme returns the current branding theme.

func (*BrandingService) ListTemplates

func (s *BrandingService) ListTemplates(ctx context.Context) ([]EmailTemplate, error)

ListTemplates returns email templates.

func (*BrandingService) RemoveDomain

func (s *BrandingService) RemoveDomain(ctx context.Context) error

RemoveDomain removes the custom domain configuration.

func (*BrandingService) SetDomain

func (s *BrandingService) SetDomain(ctx context.Context, domain string) (*CustomDomain, error)

SetDomain configures a custom domain.

func (*BrandingService) UpdateTemplate

func (s *BrandingService) UpdateTemplate(ctx context.Context, templateType string, tmpl *EmailTemplate) (*EmailTemplate, error)

UpdateTemplate updates an email template.

func (*BrandingService) UpdateTheme

func (s *BrandingService) UpdateTheme(ctx context.Context, theme *Theme) (*Theme, error)

UpdateTheme updates the branding theme.

type Client

type Client struct {
	Users         *UsersService
	Sessions      *SessionsService
	Organisations *OrganisationsService
	Permissions   *PermissionsService
	Applications  *ApplicationsService
	Products      *ProductsService
	Webhooks      *WebhooksService
	Billing       *BillingService
	Branding      *BrandingService
	Logs          *LogsService
	Connections   *ConnectionsService
	Actions       *ActionsService
	APIKeys       *APIKeysService
	Environments  *EnvironmentsService
	Events        *EventsService
	FeatureFlags  *FeatureFlagsService
	TokenRules    *TokenRulesService
	// contains filtered or unexported fields
}

Client is the main entry point for the Wocha Go SDK.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a Wocha API client configured with the given options.

func (*Client) RateLimit

func (c *Client) RateLimit() RateLimit

RateLimit returns the rate limit state from the most recent API response.

type ConfigurationFinding

type ConfigurationFinding struct {
	Code string `json:"code"`
	// Console path or documentation URL to resolve the finding
	FixUrl   string `json:"fix_url"`
	Message  string `json:"message"`
	Severity string `json:"severity"`
}

type ConfigurationHealthResponse

type ConfigurationHealthResponse struct {
	AnalysedAt string                 `json:"analysed_at"`
	Findings   []ConfigurationFinding `json:"findings"`
	TenantId   string                 `json:"tenant_id"`
}

type ConfigureScimRequest

type ConfigureScimRequest struct {
	BearerToken string `json:"bearer_token,omitempty"`
	Enabled     bool   `json:"enabled,omitempty"`
	EndpointUrl string `json:"endpoint_url,omitempty"`
}

type ConfigureSocialProviderRequest

type ConfigureSocialProviderRequest struct {
	ClientId     string   `json:"client_id"`
	ClientSecret string   `json:"client_secret,omitempty"`
	Enabled      bool     `json:"enabled,omitempty"`
	Scopes       []string `json:"scopes,omitempty"`
}

type ConflictError

type ConflictError struct {
	*APIError
}

ConflictError indicates an HTTP 409 response.

func (*ConflictError) Error

func (e *ConflictError) Error() string

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

type Connection

type Connection struct {
	// Provider-specific configuration (secrets are redacted)
	Config      json.RawMessage `json:"config"`
	CreatedAt   string          `json:"created_at"`
	Domains     []string        `json:"domains"`
	ID          string          `json:"id"`
	Name        string          `json:"name"`
	Provider    string          `json:"provider"`
	ScimEnabled bool            `json:"scim_enabled"`
	Status      string          `json:"status"`
	TenantId    string          `json:"tenant_id"`
	Type        string          `json:"type"`
	UpdatedAt   string          `json:"updated_at"`
}

type ConnectionScimDetails

type ConnectionScimDetails struct {
	// SCIM bearer token (returned once on enable or rotate)
	BearerToken string `json:"bearer_token,omitempty"`
	Enabled     bool   `json:"enabled"`
	EndpointUrl string `json:"endpoint_url"`
	LastSyncAt  string `json:"last_sync_at,omitempty"`
	SyncGroups  bool   `json:"sync_groups"`
	SyncProfile bool   `json:"sync_profile"`
}

type ConnectionTestResult

type ConnectionTestResult struct {
	Details json.RawMessage `json:"details,omitempty"`
	Message string          `json:"message"`
	Success bool            `json:"success"`
}

type ConnectionsService

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

ConnectionsService manages social, enterprise SSO, and SCIM connections.

func (*ConnectionsService) ConfigureScim

func (s *ConnectionsService) ConfigureScim(ctx context.Context, config *ScimConfig) (*ScimConfig, error)

ConfigureScim updates SCIM provisioning configuration.

func (*ConnectionsService) ConfigureSocial

func (s *ConnectionsService) ConfigureSocial(ctx context.Context, provider string, config *SocialProviderConfig) (*SocialProvider, error)

ConfigureSocial configures a social login provider.

func (*ConnectionsService) CreateEnterprise

CreateEnterprise creates an enterprise SSO connection.

func (*ConnectionsService) DeleteEnterprise

func (s *ConnectionsService) DeleteEnterprise(ctx context.Context, id string) error

DeleteEnterprise removes an enterprise SSO connection.

func (*ConnectionsService) DisableSocial

func (s *ConnectionsService) DisableSocial(ctx context.Context, provider string) error

DisableSocial disables a social login provider.

func (*ConnectionsService) GetScimConfig

func (s *ConnectionsService) GetScimConfig(ctx context.Context) (*ScimConfig, error)

GetScimConfig returns SCIM provisioning configuration.

func (*ConnectionsService) ListEnterprise

func (s *ConnectionsService) ListEnterprise(ctx context.Context) ([]EnterpriseConnection, error)

ListEnterprise returns enterprise SSO connections.

func (*ConnectionsService) ListSocial

func (s *ConnectionsService) ListSocial(ctx context.Context) ([]SocialProvider, error)

ListSocial returns configured social login providers.

type CreateActionRequest

type CreateActionRequest struct {
	Code         string          `json:"code"`
	Dependencies []string        `json:"dependencies,omitempty"`
	Name         string          `json:"name"`
	Order        int             `json:"order,omitempty"`
	Runtime      string          `json:"runtime,omitempty"`
	Secrets      json.RawMessage `json:"secrets,omitempty"`
	TimeoutMs    int             `json:"timeout_ms,omitempty"`
	Trigger      string          `json:"trigger"`
}

type CreateApiKeyRequest

type CreateApiKeyRequest struct {
	ExpiresAt   *string  `json:"expires_at,omitempty"`
	IpAllowlist []string `json:"ip_allowlist,omitempty"`
	Name        string   `json:"name"`
	Scopes      []string `json:"scopes,omitempty"`
}

type CreateApplicationRequest

type CreateApplicationRequest struct {
	ClientName              string   `json:"client_name"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	RedirectUris            []string `json:"redirect_uris,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	Scope                   string   `json:"scope,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
}

type CreateConnectionRequest

type CreateConnectionRequest struct {
	Config   json.RawMessage `json:"config"`
	Domains  []string        `json:"domains,omitempty"`
	Name     string          `json:"name"`
	Provider string          `json:"provider"`
	Status   string          `json:"status,omitempty"`
	Type     string          `json:"type"`
}

type CreateEnterpriseConnectionRequest

type CreateEnterpriseConnectionRequest struct {
	// SAML signing certificate PEM
	Certificate  string `json:"certificate,omitempty"`
	ClientId     string `json:"client_id"`
	ClientSecret string `json:"client_secret,omitempty"`
	Enabled      bool   `json:"enabled,omitempty"`
	// SAML entity ID
	EntityId  string `json:"entity_id,omitempty"`
	IssuerUrl string `json:"issuer_url"`
	Label     string `json:"label"`
	// SAML metadata URL (when applicable)
	MetadataUrl string   `json:"metadata_url,omitempty"`
	OrgID       string   `json:"org_id,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
}

type CreateEnvironmentRequest

type CreateEnvironmentRequest struct {
	Config    EnvironmentConfig `json:"config,omitempty"`
	IsDefault bool              `json:"is_default,omitempty"`
	Name      string            `json:"name"`
	Slug      string            `json:"slug,omitempty"`
}

type CreateEventDestinationRequest

type CreateEventDestinationRequest struct {
	Active bool `json:"active,omitempty"`

	Config json.RawMessage      `json:"config"`
	Name   string               `json:"name"`
	Type   EventDestinationType `json:"type"`
}

type CreateFeatureFlagRequest

type CreateFeatureFlagRequest struct {
	Code         string          `json:"code"`
	DefaultValue json.RawMessage `json:"default_value"`
	Description  string          `json:"description,omitempty"`
	Type         string          `json:"type"`
}

type CreateOrganisationRequest

type CreateOrganisationRequest struct {
	DisplayName string          `json:"display_name"`
	Metadata    json.RawMessage `json:"metadata,omitempty"`
	ParentId    string          `json:"parent_id,omitempty"`
	Slug        string          `json:"slug"`
}

type CreateProductRequest

type CreateProductRequest struct {
	Description    string          `json:"description,omitempty"`
	DisplayName    string          `json:"display_name"`
	Metadata       json.RawMessage `json:"metadata,omitempty"`
	Namespace      string          `json:"namespace"`
	SchemaFragment string          `json:"schema_fragment,omitempty"`
	Scopes         []string        `json:"scopes,omitempty"`
	Slug           string          `json:"slug"`
}

type CreateTokenRuleRequest

type CreateTokenRuleRequest struct {
	Claims      []TokenRuleClaimMapping `json:"claims,omitempty"`
	Conditions  []TokenRuleCondition    `json:"conditions,omitempty"`
	Description string                  `json:"description,omitempty"`
	Name        string                  `json:"name"`
	Priority    int                     `json:"priority,omitempty"`
	Status      string                  `json:"status,omitempty"`
	Target      string                  `json:"target"`
}

type CreateUserRequest

type CreateUserRequest struct {
	Email         string          `json:"email"`
	MetadataAdmin json.RawMessage `json:"metadata_admin,omitempty"`
	Name          string          `json:"name,omitempty"`
	Password      string          `json:"password,omitempty"`
	// Additional Kratos identity traits
	Traits json.RawMessage `json:"traits,omitempty"`
}

type CreateWebhookRequest

type CreateWebhookRequest struct {
	Events      []string           `json:"events"`
	RetryPolicy WebhookRetryPolicy `json:"retry_policy,omitempty"`
	// Optional signing secret (auto-generated if omitted)
	Secret string `json:"secret,omitempty"`
	URL    string `json:"url"`
}

type CustomDomain

type CustomDomain struct {
	Domain string `json:"domain,omitempty"`
	Status string `json:"status"`
	// DNS TXT record value for domain verification
	VerificationRecord string `json:"verification_record,omitempty"`
	VerifiedAt         string `json:"verified_at,omitempty"`
}

type EmailTemplate

type EmailTemplate struct {
	BodyHtml  string `json:"body_html"`
	BodyText  string `json:"body_text,omitempty"`
	Subject   string `json:"subject"`
	Type      string `json:"type"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

type EnterpriseConnection

type EnterpriseConnection struct {
	ClientId     string `json:"client_id"`
	DiscoveryUrl string `json:"discovery_url,omitempty"`
	Enabled      bool   `json:"enabled"`
	ID           string `json:"id"`
	IssuerUrl    string `json:"issuer_url"`
	Label        string `json:"label"`
	// Organisation scope when the connection is org-specific
	OrgID    string   `json:"org_id,omitempty"`
	Provider string   `json:"provider"`
	Scopes   []string `json:"scopes,omitempty"`
}

type EnterpriseConnectionCreateParams

type EnterpriseConnectionCreateParams = CreateEnterpriseConnectionRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type Environment

type Environment struct {
	Config    EnvironmentConfig `json:"config,omitempty"`
	CreatedAt string            `json:"created_at,omitempty"`
	ID        string            `json:"id,omitempty"`
	IsDefault bool              `json:"is_default,omitempty"`
	Name      string            `json:"name,omitempty"`
	Slug      string            `json:"slug,omitempty"`
	TenantId  string            `json:"tenant_id,omitempty"`
	UpdatedAt string            `json:"updated_at,omitempty"`
}

type EnvironmentConfig

type EnvironmentConfig struct {
	AllowedRedirectOrigins []string `json:"allowed_redirect_origins,omitempty"`
	FeatureFlagsMode       string   `json:"feature_flags_mode,omitempty"`
	IssuerUrl              string   `json:"issuer_url,omitempty"`
	WebhookUrlPrefix       string   `json:"webhook_url_prefix,omitempty"`
}

type EnvironmentCreateParams

type EnvironmentCreateParams = CreateEnvironmentRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type EnvironmentList

type EnvironmentList struct {
	Data []Environment `json:"data,omitempty"`
}

type EnvironmentPromoteParams

type EnvironmentPromoteParams = PromoteEnvironmentRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type EnvironmentUpdateParams

type EnvironmentUpdateParams = UpdateEnvironmentRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type EnvironmentsService

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

EnvironmentsService manages tenant environments.

func (*EnvironmentsService) Create

Create creates a new environment.

func (*EnvironmentsService) Delete

func (s *EnvironmentsService) Delete(ctx context.Context, id string) error

Delete deletes an environment.

func (*EnvironmentsService) Get

Get retrieves an environment by ID.

func (*EnvironmentsService) List

List returns all environments configured for the tenant.

func (*EnvironmentsService) ListAPIKeys

func (s *EnvironmentsService) ListAPIKeys(ctx context.Context, id string, params *ListParams) (*PaginatedResponse[APIKey], error)

ListAPIKeys returns API keys scoped to an environment.

func (*EnvironmentsService) Promote

Promote copies configuration from a source environment to the target environment. The response shape depends on whether dry_run is set in the request.

func (*EnvironmentsService) Update

Update updates an environment.

type ErrorCategory

type ErrorCategory string

ErrorCategory classifies SDK errors.

const (
	ErrorCategoryAPI        ErrorCategory = "api"
	ErrorCategoryNetwork    ErrorCategory = "network"
	ErrorCategoryValidation ErrorCategory = "validation"
)

type ErrorResponse

type ErrorResponse struct {
	// Link to error documentation
	DocsUrl string `json:"docs_url"`
	// Machine-readable error code
	Error string `json:"error"`
	// Human-readable error message
	Message string `json:"message"`
	// Unique request identifier for support
	RequestId string `json:"request_id"`
	// Seconds to wait before retrying (rate limit errors only)
	RetryAfter int `json:"retry_after,omitempty"`
}

type EvaluateFeatureFlagsResponse

type EvaluateFeatureFlagsResponse = FeatureFlagEvaluationResponse

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type EvaluatedFeatureFlag

type EvaluatedFeatureFlag struct {
	Code         string          `json:"code"`
	DefaultValue json.RawMessage `json:"default_value"`
	Overridden   bool            `json:"overridden"`
	Type         string          `json:"type"`
	Value        json.RawMessage `json:"value"`
}

type Event

type Event struct {
	CreatedAt string `json:"created_at"`
	// Monotonic ordering cursor (bigserial as string)
	Cursor string `json:"cursor"`
	// Event payload (same shape as webhook data)
	Data json.RawMessage `json:"data"`
	ID   string          `json:"id"`
	Type EventType       `json:"type"`
}

type EventDestination

type EventDestination struct {
	Active    bool                 `json:"active"`
	Config    json.RawMessage      `json:"config"`
	CreatedAt string               `json:"created_at"`
	ID        string               `json:"id"`
	Name      string               `json:"name"`
	TenantId  string               `json:"tenant_id"`
	Type      EventDestinationType `json:"type"`
	UpdatedAt string               `json:"updated_at"`
}

type EventDestinationType

type EventDestinationType string

EventDestinationType is an OpenAPI enum schema.

type EventList

type EventList struct {
	Data         []Event         `json:"data"`
	ListMetadata json.RawMessage `json:"list_metadata"`
}

type EventListMetadata

type EventListMetadata struct {
	After string `json:"after"`
}

EventListMetadata holds cursor pagination metadata for events.

type EventListParams

type EventListParams struct {
	After      string
	Limit      int
	EventTypes []string
	RangeStart string
	RangeEnd   string
}

EventListParams configures event list queries.

type EventListResponse

type EventListResponse struct {
	Data         []PlatformEvent   `json:"data"`
	ListMetadata EventListMetadata `json:"list_metadata"`
}

EventListResponse is the paginated events envelope.

type EventType

type EventType string

EventType is an OpenAPI enum schema.

type EventsService

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

EventsService queries the ordered, replayable tenant event stream.

func (*EventsService) Get

func (s *EventsService) Get(ctx context.Context, id string) (*PlatformEvent, error)

Get retrieves an event by ID.

func (*EventsService) List

List returns a paginated list of events.

func (*EventsService) ListAll

func (s *EventsService) ListAll(ctx context.Context, params *EventListParams) ([]PlatformEvent, error)

ListAll fetches all events across cursor pages.

type ExpandRequest

type ExpandRequest struct {
	Resource   ObjectRef `json:"resource"`
	Permission string    `json:"permission"`
}

ExpandRequest expands a permission tree.

type ExpandResponse

type ExpandResponse struct {
	Tree any `json:"tree"`
}

ExpandResponse contains a permission expansion tree.

type FeatureFlag

type FeatureFlag struct {
	Code         string                `json:"code"`
	CreatedAt    string                `json:"created_at"`
	DefaultValue json.RawMessage       `json:"default_value"`
	Description  string                `json:"description,omitempty"`
	ID           string                `json:"id"`
	Overrides    []FeatureFlagOverride `json:"overrides,omitempty"`
	TenantId     string                `json:"tenant_id"`
	Type         string                `json:"type"`
	UpdatedAt    string                `json:"updated_at"`
}

type FeatureFlagCreateParams

type FeatureFlagCreateParams = CreateFeatureFlagRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type FeatureFlagEvaluateParams

type FeatureFlagEvaluateParams struct {
	UserID         string
	OrganisationID string
	EnvironmentID  string
}

FeatureFlagEvaluateParams configures feature flag evaluation.

type FeatureFlagEvaluationResponse

type FeatureFlagEvaluationResponse struct {
	Context json.RawMessage        `json:"context"`
	Flags   []EvaluatedFeatureFlag `json:"flags"`
}

type FeatureFlagList

type FeatureFlagList struct {
	Data []FeatureFlag `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type FeatureFlagListParams

type FeatureFlagListParams struct {
	ListParams
	IncludeOverrides bool
}

FeatureFlagListParams configures feature flag list queries.

type FeatureFlagOverride

type FeatureFlagOverride struct {
	CreatedAt string          `json:"created_at"`
	FlagId    string          `json:"flag_id"`
	ID        string          `json:"id"`
	Scope     string          `json:"scope"`
	ScopeId   string          `json:"scope_id"`
	Value     json.RawMessage `json:"value"`
}

type FeatureFlagOverrideParams

type FeatureFlagOverrideParams = SetFeatureFlagOverrideRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type FeatureFlagUpdateParams

type FeatureFlagUpdateParams = UpdateFeatureFlagRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type FeatureFlagsService

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

FeatureFlagsService manages tenant feature flags and scoped overrides.

func (*FeatureFlagsService) Create

Create creates a feature flag.

func (*FeatureFlagsService) Delete

func (s *FeatureFlagsService) Delete(ctx context.Context, id string) error

Delete permanently deletes a feature flag.

func (*FeatureFlagsService) Evaluate

Evaluate evaluates feature flags for a given context.

func (*FeatureFlagsService) Get

Get retrieves a feature flag by ID.

func (*FeatureFlagsService) List

List returns a paginated list of feature flags.

func (*FeatureFlagsService) SetOverride

SetOverride sets a scoped override for a feature flag.

func (*FeatureFlagsService) Update

Update updates a feature flag.

type InternalOrgMetadataResponse

type InternalOrgMetadataResponse struct {
	MfaEnforcement           string `json:"mfa_enforcement"`
	OrgID                    string `json:"org_id"`
	RequirePhoneVerification bool   `json:"require_phone_verification"`
	// Per-organisation security policy overrides (null fields inherit from tenant)
	SecurityPolicy        OrgSecurityPolicyOverrides `json:"security_policy"`
	SessionTimeoutMinutes int                        `json:"session_timeout_minutes,omitempty"`
}

type InternalSmsMfaChallengeRequest

type InternalSmsMfaChallengeRequest struct {
	// Optional application name for SMS template rendering
	AppName    string `json:"app_name,omitempty"`
	IdentityId string `json:"identity_id"`
	TenantId   string `json:"tenant_id"`
}

type InternalSmsMfaChallengeResponse

type InternalSmsMfaChallengeResponse struct {
	PhoneNumberMasked string `json:"phone_number_masked"`
	Status            string `json:"status"`
}

type InternalSmsMfaVerifyRequest

type InternalSmsMfaVerifyRequest struct {
	Code       string `json:"code"`
	IdentityId string `json:"identity_id"`
	TenantId   string `json:"tenant_id"`
}

type InternalSmsMfaVerifyResponse

type InternalSmsMfaVerifyResponse struct {
	Status string `json:"status"`
}

type JWTValidationError

type JWTValidationError struct {
	Code    string
	Message string
	Cause   error
}

JWTValidationError is returned when token validation fails.

func (*JWTValidationError) Error

func (e *JWTValidationError) Error() string

func (*JWTValidationError) Unwrap

func (e *JWTValidationError) Unwrap() error

type JWTValidator

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

JWTValidator validates Wocha JWT access tokens using the JWKS endpoint.

func NewJWTValidator

func NewJWTValidator(config JWTValidatorConfig) (*JWTValidator, error)

NewJWTValidator creates a new JWT validator with the given configuration.

func (*JWTValidator) Middleware

func (v *JWTValidator) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that validates the bearer token and stores claims in the request context. Unauthenticated requests receive a 401 JSON response.

func (*JWTValidator) Validate

func (v *JWTValidator) Validate(token string) (*AccessTokenClaims, error)

Validate verifies a JWT access token and returns the claims.

type JWTValidatorConfig

type JWTValidatorConfig struct {
	// Issuer is the expected token issuer (e.g. "https://auth.example.com").
	// Also used to resolve the JWKS endpoint at {Issuer}/.well-known/jwks.json.
	Issuer string

	// Audience is the expected audience claim. If empty, audience is not checked.
	Audience string

	// JWKSUrl overrides the JWKS endpoint URL. If empty, derived from Issuer.
	JWKSUrl string

	// HTTPClient is an optional HTTP client for fetching JWKS. Defaults to
	// http.DefaultClient with a 10-second timeout.
	HTTPClient *http.Client

	// JWKSCacheTTL controls how long JWKS keys are cached. Defaults to 5 minutes.
	JWKSCacheTTL time.Duration

	// ClockSkew is the maximum allowed clock skew for exp/nbf checks.
	// Defaults to 30 seconds.
	ClockSkew time.Duration
}

JWTValidatorConfig configures JWT validation for a resource server.

type ListParams

type ListParams struct {
	// PageSize is the number of items per page (maps to page_size).
	PageSize int
	// PageToken is the cursor from a previous response (maps to page_token).
	PageToken string
}

ListParams configures pagination for list endpoints.

type ListRelationshipsFilters

type ListRelationshipsFilters struct {
	ResourceType string
	ResourceID   string
	Relation     string
}

ListRelationshipsFilters filters relationship list queries.

type LogEntry

type LogEntry map[string]json.RawMessage

Auth or audit event record

type LogExportParams

type LogExportParams struct {
	LogFilter
	Format string
}

LogExportParams configures log export requests.

type LogFilter

type LogFilter struct {
	ListParams
	Since string
	Until string
}

LogFilter configures log list queries.

type LogList

type LogList struct {
	Data          []LogEntry `json:"data"`
	HasMore       bool       `json:"has_more,omitempty"`
	NextPageToken *string    `json:"next_page_token,omitempty"`
}

type LogsService

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

LogsService queries authentication and audit logs.

func (*LogsService) ExportLogs

func (s *LogsService) ExportLogs(ctx context.Context, params *LogExportParams) (string, error)

ExportLogs exports logs as CSV or JSON text.

func (*LogsService) ListAuditLogs

func (s *LogsService) ListAuditLogs(ctx context.Context, filter *LogFilter) (*PaginatedResponse[AuditLogEntry], error)

ListAuditLogs returns management audit log entries.

func (*LogsService) ListAuthLogs

func (s *LogsService) ListAuthLogs(ctx context.Context, filter *LogFilter) (*PaginatedResponse[AuthLogEntry], error)

ListAuthLogs returns authentication log entries.

type LookupRequest

type LookupRequest struct {
	ResourceType string    `json:"resource_type"`
	Permission   string    `json:"permission"`
	Subject      ObjectRef `json:"subject"`
}

LookupRequest finds resources a subject can access.

type LookupResponse

type LookupResponse struct {
	ResourceIDs []string `json:"resource_ids"`
}

LookupResponse contains resource IDs from a permission lookup.

type NotFoundError

type NotFoundError struct {
	*APIError
}

NotFoundError indicates an HTTP 404 response.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type ObjectRef

type ObjectRef struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

ObjectRef identifies a resource or subject in permission operations.

type ObjectReference

type ObjectReference struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

type Option

type Option func(*Client)

Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the Management API key or OAuth 2.0 access token.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets an explicit API base URL (e.g. for self-hosted deployments).

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retries on 429/5xx responses.

func WithTenant

func WithTenant(tenant string) Option

WithTenant sets the tenant slug. The base URL resolves to https://{tenant}.api.wocha.ai/v1 unless WithBaseURL is also set.

func WithTenantHeader

func WithTenantHeader(tenantID string) Option

WithTenantHeader sets the X-Tenant-ID header for self-hosted deployments where the tenant is not encoded in the base URL.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout.

type OrgMember

type OrgMember struct {
	CreatedAt  string          `json:"created_at,omitempty"`
	IdentityId string          `json:"identity_id,omitempty"`
	Metadata   json.RawMessage `json:"metadata,omitempty"`
	Role       string          `json:"role,omitempty"`
}

type OrgMemberAddParams

type OrgMemberAddParams = AddOrgMemberRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type OrgMemberAdded

type OrgMemberAdded struct {
	IdentityId     string `json:"identity_id,omitempty"`
	OrganisationId string `json:"organisation_id,omitempty"`
	Role           string `json:"role,omitempty"`
}

type OrgMemberUpdateParams

type OrgMemberUpdateParams = UpdateOrgMemberRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type OrgSecurityPolicyOverrides

type OrgSecurityPolicyOverrides struct {
	AllowedFactors            json.RawMessage `json:"allowedFactors,omitempty"`
	GracePeriodMs             *int            `json:"gracePeriodMs,omitempty"`
	MfaEnforcement            *string         `json:"mfaEnforcement,omitempty"`
	MfaPolicy                 *string         `json:"mfaPolicy,omitempty"`
	PasswordDisallowReuse     *int            `json:"passwordDisallowReuse,omitempty"`
	PasswordHibpCheck         *bool           `json:"passwordHibpCheck,omitempty"`
	PasswordMaxAgeDays        *int            `json:"passwordMaxAgeDays,omitempty"`
	PasswordMinLength         *int            `json:"passwordMinLength,omitempty"`
	PasswordRequireLowercase  *bool           `json:"passwordRequireLowercase,omitempty"`
	PasswordRequireNumber     *bool           `json:"passwordRequireNumber,omitempty"`
	PasswordRequireSymbol     *bool           `json:"passwordRequireSymbol,omitempty"`
	PasswordRequireUppercase  *bool           `json:"passwordRequireUppercase,omitempty"`
	PreferredFactor           *string         `json:"preferredFactor,omitempty"`
	SessionIdleTimeoutMinutes *int            `json:"sessionIdleTimeoutMinutes,omitempty"`
	SessionTimeoutMinutes     *int            `json:"sessionTimeoutMinutes,omitempty"`
	UnenrolledUserAction      *string         `json:"unenrolledUserAction,omitempty"`
}

Per-organisation security policy overrides (null fields inherit from tenant)

type Organisation

type Organisation struct {
	CreatedAt   string          `json:"created_at"`
	DisplayName string          `json:"display_name"`
	ID          string          `json:"id"`
	Metadata    json.RawMessage `json:"metadata,omitempty"`
	ParentId    *string         `json:"parent_id,omitempty"`
	Slug        string          `json:"slug"`
	UpdatedAt   string          `json:"updated_at,omitempty"`
}

type OrganisationCreateParams

type OrganisationCreateParams = CreateOrganisationRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type OrganisationSecurityPolicyResponse

type OrganisationSecurityPolicyResponse struct {
	// Per-field inheritance indicators (true = using tenant default)
	Inherited                 json.RawMessage `json:"_inherited"`
	AllowedFactors            []string        `json:"allowedFactors"`
	GracePeriodMs             int             `json:"gracePeriodMs"`
	MfaEnforcement            string          `json:"mfaEnforcement"`
	MfaPolicy                 string          `json:"mfaPolicy"`
	OrgID                     string          `json:"org_id"`
	PasswordDisallowReuse     int             `json:"passwordDisallowReuse,omitempty"`
	PasswordHibpCheck         bool            `json:"passwordHibpCheck"`
	PasswordMaxAgeDays        int             `json:"passwordMaxAgeDays,omitempty"`
	PasswordMinLength         int             `json:"passwordMinLength"`
	PasswordRequireLowercase  bool            `json:"passwordRequireLowercase"`
	PasswordRequireNumber     bool            `json:"passwordRequireNumber"`
	PasswordRequireSymbol     bool            `json:"passwordRequireSymbol"`
	PasswordRequireUppercase  bool            `json:"passwordRequireUppercase"`
	PreferredFactor           string          `json:"preferredFactor,omitempty"`
	RequirePhoneVerification  bool            `json:"requirePhoneVerification,omitempty"`
	SessionIdleTimeoutMinutes int             `json:"sessionIdleTimeoutMinutes,omitempty"`
	SessionTimeoutMinutes     int             `json:"sessionTimeoutMinutes,omitempty"`
	TenantId                  string          `json:"tenant_id"`
	UnenrolledUserAction      string          `json:"unenrolledUserAction"`
}

type OrganisationTreeNode

type OrganisationTreeNode struct {
	Children    []OrganisationTreeNode `json:"children"`
	DisplayName string                 `json:"display_name"`
	ID          string                 `json:"id"`
	ParentId    *string                `json:"parent_id,omitempty"`
	Slug        string                 `json:"slug"`
}

type OrganisationTreeResponse

type OrganisationTreeResponse struct {
	// Ancestor organisation IDs from root to parent
	Ancestors []string             `json:"ancestors"`
	OrgId     string               `json:"orgId"`
	Tree      OrganisationTreeNode `json:"tree"`
}

type OrganisationUpdateParams

type OrganisationUpdateParams = UpdateOrganisationRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type OrganisationsService

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

OrganisationsService manages organisations and members.

func (*OrganisationsService) AddMember

func (s *OrganisationsService) AddMember(ctx context.Context, orgID string, params *OrgMemberAddParams) (*OrgMember, error)

AddMember adds a member to an organisation.

func (*OrganisationsService) Create

Create creates a new organisation.

func (*OrganisationsService) Delete

func (s *OrganisationsService) Delete(ctx context.Context, id string) error

Delete deletes an organisation.

func (*OrganisationsService) Get

Get retrieves an organisation by ID.

func (*OrganisationsService) GetTree

func (s *OrganisationsService) GetTree(ctx context.Context, orgID string) ([]Organisation, error)

GetTree returns the organisation hierarchy tree.

func (*OrganisationsService) List

List returns a paginated list of organisations.

func (*OrganisationsService) ListAll

func (s *OrganisationsService) ListAll(ctx context.Context, params *ListParams) ([]Organisation, error)

ListAll fetches all organisations across pages.

func (*OrganisationsService) ListMembers

func (s *OrganisationsService) ListMembers(ctx context.Context, orgID string, params *ListParams) (*PaginatedResponse[OrgMember], error)

ListMembers returns members of an organisation.

func (*OrganisationsService) RemoveMember

func (s *OrganisationsService) RemoveMember(ctx context.Context, orgID, memberID string) error

RemoveMember removes a member from an organisation.

func (*OrganisationsService) Update

Update updates an organisation.

func (*OrganisationsService) UpdateMember

func (s *OrganisationsService) UpdateMember(ctx context.Context, orgID, memberID string, params *OrgMemberUpdateParams) (*OrgMember, error)

UpdateMember updates a member's role.

type PaginatedList

type PaginatedList struct {
	Data json.RawMessage `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type PaginatedResponse

type PaginatedResponse[T any] struct {
	Data          []T    `json:"data"`
	Total         *int   `json:"total,omitempty"`
	NextPageToken string `json:"next_page_token,omitempty"`
	HasMore       bool   `json:"has_more"`
}

PaginatedResponse is the standard paginated list envelope.

type PasswordPolicy

type PasswordPolicy struct {
	// Disallow reuse of the last N passwords (0 = disabled)
	DisallowReuse int  `json:"disallowReuse,omitempty"`
	HibpCheck     bool `json:"hibpCheck"`
	// Force password rotation after this many days (0 = no expiry)
	MaxAgeDays       int  `json:"maxAgeDays,omitempty"`
	MinLength        int  `json:"minLength"`
	RequireLowercase bool `json:"requireLowercase"`
	RequireNumber    bool `json:"requireNumber"`
	RequireSymbol    bool `json:"requireSymbol"`
	RequireUppercase bool `json:"requireUppercase"`
}

type PasswordPolicyResponse

type PasswordPolicyResponse struct {
	// Disallow reuse of the last N passwords (0 = disabled)
	DisallowReuse int  `json:"disallowReuse,omitempty"`
	HibpCheck     bool `json:"hibpCheck"`
	// Force password rotation after this many days (0 = no expiry)
	MaxAgeDays       int    `json:"maxAgeDays,omitempty"`
	MinLength        int    `json:"minLength"`
	RequireLowercase bool   `json:"requireLowercase"`
	RequireNumber    bool   `json:"requireNumber"`
	RequireSymbol    bool   `json:"requireSymbol"`
	RequireUppercase bool   `json:"requireUppercase"`
	TenantId         string `json:"tenant_id"`
}

type PermissionCheckParams

type PermissionCheckParams struct {
	UserID       string
	Permission   string
	ResourceType string
	ResourceID   string
	Context      json.RawMessage `json:"context,omitempty"`
}

PermissionCheckParams is a convenience wrapper for permission checks.

type PermissionCheckRequest

type PermissionCheckRequest struct {
	Context    json.RawMessage `json:"context,omitempty"`
	Permission string          `json:"permission"`
	Resource   ObjectReference `json:"resource"`
	Subject    ObjectReference `json:"subject"`
}

type PermissionCheckResponse

type PermissionCheckResponse struct {
	Allowed        bool   `json:"allowed"`
	Permissionship string `json:"permissionship,omitempty"`
	ResolvedAt     string `json:"resolved_at,omitempty"`
}

type PermissionError

type PermissionError struct {
	*APIError
}

PermissionError indicates an HTTP 403 response.

func (*PermissionError) Error

func (e *PermissionError) Error() string

func (*PermissionError) Unwrap

func (e *PermissionError) Unwrap() error

type PermissionExpandRequest

type PermissionExpandRequest struct {
	Permission string          `json:"permission"`
	Resource   ObjectReference `json:"resource"`
}

type PermissionExpandResponse

type PermissionExpandResponse struct {
	// SpiceDB permission expansion tree
	Tree json.RawMessage `json:"tree,omitempty"`
}

type PermissionLookupRequest

type PermissionLookupRequest struct {
	Permission string `json:"permission"`
	// SpiceDB resource object type to search
	ResourceType string          `json:"resource_type"`
	Subject      ObjectReference `json:"subject"`
}

type PermissionLookupResponse

type PermissionLookupResponse struct {
	ResourceIds []string `json:"resource_ids"`
}

type PermissionSchemaResponse

type PermissionSchemaResponse struct {
	// SpiceDB schema definition text
	Schema string `json:"schema"`
}

type PermissionsService

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

PermissionsService manages permission checks and SpiceDB relationships.

func (*PermissionsService) Check

Check evaluates whether a subject has a permission on a resource.

func (*PermissionsService) DeleteRelationship

func (s *PermissionsService) DeleteRelationship(ctx context.Context, rel *Relationship) error

DeleteRelationship removes a relationship tuple.

func (*PermissionsService) Expand

Expand expands a permission tree.

func (*PermissionsService) GetSchema

func (s *PermissionsService) GetSchema(ctx context.Context) (string, error)

GetSchema returns the permission schema.

func (*PermissionsService) ListRelationships

func (s *PermissionsService) ListRelationships(ctx context.Context, filters *ListRelationshipsFilters) ([]Relationship, error)

ListRelationships lists SpiceDB relationships.

func (*PermissionsService) Lookup

Lookup finds resources a subject can access.

func (*PermissionsService) UpdateSchema

func (s *PermissionsService) UpdateSchema(ctx context.Context, schema string) (string, error)

UpdateSchema updates the permission schema.

func (*PermissionsService) WriteRelationship

func (s *PermissionsService) WriteRelationship(ctx context.Context, rel *Relationship) error

WriteRelationship creates a relationship tuple.

type PhoneRemoved

type PhoneRemoved struct {
	Status string `json:"status"`
}

type PhoneRemovedResponse

type PhoneRemovedResponse struct {
	Data PhoneRemoved `json:"data"`
}

type PhoneVerificationPending

type PhoneVerificationPending struct {
	PhoneNumberMasked string `json:"phone_number_masked"`
	Status            string `json:"status"`
}

type PhoneVerificationPendingResponse

type PhoneVerificationPendingResponse struct {
	Data PhoneVerificationPending `json:"data"`
}

type PhoneVerificationStartRequest

type PhoneVerificationStartRequest struct {
	// E.164 phone number (e.g. +447911123456)
	PhoneNumber string `json:"phone_number"`
}

type PhoneVerified

type PhoneVerified struct {
	PhoneNumber string `json:"phone_number"`
	Status      string `json:"status"`
}

type PhoneVerifiedResponse

type PhoneVerifiedResponse struct {
	Data PhoneVerified `json:"data"`
}

type PhoneVerifyRequest

type PhoneVerifyRequest struct {
	// 6-digit SMS verification code
	Code string `json:"code"`
}

type PlatformEvent

type PlatformEvent = Event

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type PortalSession

type PortalSession struct {
	URL string `json:"url"`
}

PortalSession is a Stripe billing portal redirect URL.

type Product

type Product struct {
	CreatedAt   string          `json:"created_at"`
	Description *string         `json:"description,omitempty"`
	DisplayName string          `json:"display_name"`
	ID          string          `json:"id"`
	Metadata    json.RawMessage `json:"metadata"`
	// SpiceDB namespace for this product
	Namespace     string  `json:"namespace"`
	OwnerTenantId *string `json:"owner_tenant_id,omitempty"`
	// SpiceDB schema fragment for this product
	SchemaFragment *string  `json:"schema_fragment,omitempty"`
	Scopes         []string `json:"scopes"`
	Slug           string   `json:"slug"`
	Status         string   `json:"status"`
	UpdatedAt      string   `json:"updated_at"`
}

type ProductCreateParams

type ProductCreateParams = CreateProductRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type ProductListParams

type ProductListParams struct {
	Status        string
	OwnerTenantID string
}

ProductListParams filters product list queries.

type ProductListResponse

type ProductListResponse struct {
	Products []Product `json:"products"`
	Total    int       `json:"total"`
}

type ProductResponse

type ProductResponse struct {
	Product Product `json:"product"`
}

type ProductScopeEntry

type ProductScopeEntry struct {
	ProductName string `json:"product_name"`
	ProductSlug string `json:"product_slug"`
	Scope       string `json:"scope"`
}

type ProductScopesResponse

type ProductScopesResponse struct {
	Scopes []ProductScopeEntry `json:"scopes"`
	Total  int                 `json:"total"`
}

type ProductUpdateParams

type ProductUpdateParams = UpdateProductRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type ProductsService

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

ProductsService manages products in the Wocha product registry.

func (*ProductsService) Create

func (s *ProductsService) Create(ctx context.Context, params *ProductCreateParams) (*Product, error)

Create creates a new product.

func (*ProductsService) Delete

func (s *ProductsService) Delete(ctx context.Context, id string) (bool, error)

Delete deletes a product.

func (*ProductsService) Get

func (s *ProductsService) Get(ctx context.Context, idOrSlug string) (*Product, error)

Get retrieves a product by ID or slug.

func (*ProductsService) List

List returns products matching the given filters.

func (*ProductsService) ListScopes

ListScopes returns all registered OAuth scopes.

func (*ProductsService) Update

func (s *ProductsService) Update(ctx context.Context, id string, params *ProductUpdateParams) (*Product, error)

Update updates a product.

type PromoteEnvironmentDryRunResponse

type PromoteEnvironmentDryRunResponse struct {
	DryRun         bool              `json:"dry_run,omitempty"`
	PromotedConfig EnvironmentConfig `json:"promoted_config,omitempty"`
	Source         Environment       `json:"source,omitempty"`
	Target         Environment       `json:"target,omitempty"`
}

type PromoteEnvironmentRequest

type PromoteEnvironmentRequest struct {
	DryRun              bool   `json:"dry_run,omitempty"`
	SourceEnvironmentId string `json:"source_environment_id,omitempty"`
	SourceSlug          string `json:"source_slug,omitempty"`
}

type QuotaLimit

type QuotaLimit struct {
	// Whether additional usage is permitted
	Allowed bool `json:"allowed,omitempty"`
	// Current usage in the billing period
	Current int `json:"current,omitempty"`
	// Plan limit (-1 = unlimited)
	Limit int `json:"limit,omitempty"`
}

type RateLimit

type RateLimit struct {
	Limit     int
	Remaining int
	Reset     int64
}

RateLimit holds parsed X-RateLimit-* response headers from the last request.

type RateLimitError

type RateLimitError struct {
	*APIError
}

RateLimitError indicates an HTTP 429 response.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

type RecoveryLinkResponse

type RecoveryLinkResponse struct {
	ExpiresAt    string `json:"expires_at,omitempty"`
	RecoveryLink string `json:"recovery_link,omitempty"`
}

type Relationship

type Relationship struct {
	Resource ObjectRef `json:"resource"`
	Relation string    `json:"relation"`
	Subject  ObjectRef `json:"subject"`
}

Relationship is a SpiceDB relationship tuple (SDK wire shape).

type RotateApiKeyRequest

type RotateApiKeyRequest struct {
	// Seconds the previous key remains valid after rotation
	RotationGracePeriod int `json:"rotation_grace_period,omitempty"`
}

type RotateApiKeyResponse

type RotateApiKeyResponse struct {
	// New API key secret
	Key         string `json:"key"`
	NewKey      ApiKey `json:"new_key"`
	PreviousKey ApiKey `json:"previous_key"`
	RotatedAt   string `json:"rotated_at"`
}

type RotateSecretResponse

type RotateSecretResponse struct {
	ClientId     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	RotatedAt    string `json:"rotated_at"`
}

type ScimConfig

type ScimConfig struct {
	// Bearer token for SCIM endpoint authentication
	BearerToken string `json:"bearer_token,omitempty"`
	Enabled     bool   `json:"enabled"`
	EndpointUrl string `json:"endpoint_url,omitempty"`
	LastSyncAt  string `json:"last_sync_at,omitempty"`
}

type SdkTelemetryBatchRequest

type SdkTelemetryBatchRequest struct {
	Events []SdkTelemetryEvent `json:"events"`
}

type SdkTelemetryBatchResponse

type SdkTelemetryBatchResponse struct {
	// Number of telemetry events stored
	Accepted int `json:"accepted"`
}

type SdkTelemetryEvent

type SdkTelemetryEvent struct {
	AuthMethod  string          `json:"auth_method,omitempty"`
	Framework   string          `json:"framework"`
	Metrics     json.RawMessage `json:"metrics"`
	NodeVersion string          `json:"node_version,omitempty"`
	ReportedAt  string          `json:"reported_at,omitempty"`
	Runtime     string          `json:"runtime,omitempty"`
	SdkVersion  string          `json:"sdk_version"`
}

type ServerError

type ServerError struct {
	*APIError
}

ServerError indicates an HTTP 5xx response or network failure.

func (*ServerError) Error

func (e *ServerError) Error() string

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

type Session

type Session struct {
	Aal             string `json:"aal,omitempty"`
	Active          bool   `json:"active,omitempty"`
	AuthenticatedAt string `json:"authenticated_at,omitempty"`
	ExpiresAt       string `json:"expires_at,omitempty"`
	ID              string `json:"id,omitempty"`
	IdentityId      string `json:"identity_id,omitempty"`
}

type SessionsService

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

SessionsService manages user sessions.

func (*SessionsService) List

func (s *SessionsService) List(ctx context.Context, userID string, params *ListParams) (*PaginatedResponse[Session], error)

List returns sessions for a user.

func (*SessionsService) ListActive

func (s *SessionsService) ListActive(ctx context.Context, params *ListParams) (*PaginatedResponse[Session], error)

ListActive returns active sessions across the tenant.

func (*SessionsService) ListAll

func (s *SessionsService) ListAll(ctx context.Context, userID string, params *ListParams) ([]Session, error)

ListAll fetches all sessions for a user across pages.

func (*SessionsService) PurgeAll

func (s *SessionsService) PurgeAll(ctx context.Context) error

PurgeAll deletes all tenant sessions.

func (*SessionsService) Revoke

func (s *SessionsService) Revoke(ctx context.Context, userID, sessionID string) error

Revoke revokes a specific session.

func (*SessionsService) RevokeAll

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

RevokeAll revokes all sessions for a user.

type SetFeatureFlagOverrideRequest

type SetFeatureFlagOverrideRequest struct {
	Scope   string          `json:"scope"`
	ScopeId string          `json:"scope_id"`
	Value   json.RawMessage `json:"value"`
}

type SmsMfaEnrollmentPending

type SmsMfaEnrollmentPending struct {
	PhoneNumberMasked string `json:"phone_number_masked"`
	Status            string `json:"status"`
}

type SmsMfaEnrollmentPendingResponse

type SmsMfaEnrollmentPendingResponse struct {
	Data SmsMfaEnrollmentPending `json:"data"`
}

type SmsMfaVerifyRequest

type SmsMfaVerifyRequest struct {
	// 6-digit SMS verification code
	Code string `json:"code"`
}

type SocialProvider

type SocialProvider struct {
	ClientId string   `json:"client_id,omitempty"`
	Enabled  bool     `json:"enabled"`
	Label    string   `json:"label"`
	Provider string   `json:"provider"`
	Scopes   []string `json:"scopes,omitempty"`
}

type SocialProviderConfig

type SocialProviderConfig = ConfigureSocialProviderRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type Subscription

type Subscription struct {
	BillingConfigured bool    `json:"billing_configured,omitempty"`
	CreatedAt         string  `json:"created_at,omitempty"`
	CustomDomain      *string `json:"custom_domain,omitempty"`
	PlanTier          string  `json:"plan_tier,omitempty"`
	Region            string  `json:"region,omitempty"`
	Status            string  `json:"status,omitempty"`
	TenantId          string  `json:"tenant_id,omitempty"`
}

type Theme

type Theme = Branding

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type TokenRule

type TokenRule struct {
	Claims      []TokenRuleClaimMapping `json:"claims"`
	Conditions  []TokenRuleCondition    `json:"conditions"`
	CreatedAt   string                  `json:"created_at"`
	Description string                  `json:"description,omitempty"`
	ID          string                  `json:"id"`
	Name        string                  `json:"name"`
	Priority    int                     `json:"priority"`
	Status      string                  `json:"status"`
	Target      string                  `json:"target"`
	TenantId    string                  `json:"tenant_id"`
	UpdatedAt   string                  `json:"updated_at"`
}

type TokenRuleClaimMapping

type TokenRuleClaimMapping struct {
	ClaimName string          `json:"claim_name"`
	Source    json.RawMessage `json:"source"`
}

type TokenRuleCondition

type TokenRuleCondition struct {
	// Dot-notation field path (e.g. `user.email`, `organisation.id`)
	Field    string          `json:"field"`
	Operator string          `json:"operator"`
	Value    json.RawMessage `json:"value"`
}

type TokenRuleCreateParams

type TokenRuleCreateParams = CreateTokenRuleRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type TokenRuleList

type TokenRuleList struct {
	Data []TokenRule `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type TokenRuleTestContext

type TokenRuleTestContext struct {
	Connection   json.RawMessage `json:"connection,omitempty"`
	Organisation json.RawMessage `json:"organisation,omitempty"`
	User         json.RawMessage `json:"user,omitempty"`
}

type TokenRuleTestResult

type TokenRuleTestResult struct {
	Claims  json.RawMessage `json:"claims"`
	Errors  []string        `json:"errors"`
	Matched bool            `json:"matched"`
}

type TokenRuleUpdateParams

type TokenRuleUpdateParams = UpdateTokenRuleRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type TokenRulesService

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

TokenRulesService manages JWT token claim rules.

func (*TokenRulesService) Create

Create creates a new token rule.

func (*TokenRulesService) Delete

func (s *TokenRulesService) Delete(ctx context.Context, id string) error

Delete deletes a token rule.

func (*TokenRulesService) Get

func (s *TokenRulesService) Get(ctx context.Context, id string) (*TokenRule, error)

Get retrieves a token rule by ID.

func (*TokenRulesService) List

List returns a paginated list of token rules.

func (*TokenRulesService) ListAll

func (s *TokenRulesService) ListAll(ctx context.Context, params *ListParams) ([]TokenRule, error)

ListAll fetches all token rules across pages.

func (*TokenRulesService) Test

Test dry-runs a token rule against a sample evaluation context.

func (*TokenRulesService) Update

Update updates a token rule.

type TotpEnrollment

type TotpEnrollment struct {
	BackupCodes []string `json:"backup_codes"`
	// otpauth:// URI for QR code generation
	QrUri string `json:"qr_uri"`
	// Base32-encoded TOTP secret
	Secret string `json:"secret"`
}

type TotpEnrollmentResponse

type TotpEnrollmentResponse struct {
	Data TotpEnrollment `json:"data"`
}

type TotpVerifyRequest

type TotpVerifyRequest struct {
	// 6-digit TOTP code from the authenticator app
	Code string `json:"code"`
}

type TriggerActionOrderResponse

type TriggerActionOrderResponse struct {
	Actions []Action `json:"actions"`
	Trigger string   `json:"trigger"`
	Updated int      `json:"updated"`
}

type UpdateAccountProfileRequest

type UpdateAccountProfileRequest struct {
	AvatarUrl   *string `json:"avatar_url,omitempty"`
	DisplayName string  `json:"display_name,omitempty"`
	// User-editable metadata keys (locale, timezone, bio, phone, preferences)
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

type UpdateActionRequest

type UpdateActionRequest struct {
	Code         string          `json:"code,omitempty"`
	Dependencies []string        `json:"dependencies,omitempty"`
	Name         string          `json:"name,omitempty"`
	Order        int             `json:"order,omitempty"`
	Runtime      string          `json:"runtime,omitempty"`
	Secrets      json.RawMessage `json:"secrets,omitempty"`
	Status       string          `json:"status,omitempty"`
	TimeoutMs    int             `json:"timeout_ms,omitempty"`
	Trigger      string          `json:"trigger,omitempty"`
}

type UpdateApiKeyRequest

type UpdateApiKeyRequest struct {
	IpAllowlist []string `json:"ip_allowlist,omitempty"`
	Name        string   `json:"name,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
}

type UpdateApplicationRequest

type UpdateApplicationRequest struct {
	ClientName    string   `json:"client_name,omitempty"`
	GrantTypes    []string `json:"grant_types,omitempty"`
	RedirectUris  []string `json:"redirect_uris,omitempty"`
	ResponseTypes []string `json:"response_types,omitempty"`
	Scope         string   `json:"scope,omitempty"`
}

type UpdateBrandingRequest

type UpdateBrandingRequest struct {
	BackgroundColour string `json:"background_colour,omitempty"`
	CompanyName      string `json:"company_name,omitempty"`
	CustomCss        string `json:"custom_css,omitempty"`
	FaviconUrl       string `json:"favicon_url,omitempty"`
	FontFamily       string `json:"font_family,omitempty"`
	LogoUrl          string `json:"logo_url,omitempty"`
	PrimaryColour    string `json:"primary_colour,omitempty"`
}

type UpdateConnectionRequest

type UpdateConnectionRequest struct {
	Config  json.RawMessage `json:"config,omitempty"`
	Domains []string        `json:"domains,omitempty"`
	Name    string          `json:"name,omitempty"`
	Status  string          `json:"status,omitempty"`
}

type UpdateEmailTemplateRequest

type UpdateEmailTemplateRequest struct {
	BodyHtml string `json:"body_html,omitempty"`
	BodyText string `json:"body_text,omitempty"`
	Subject  string `json:"subject,omitempty"`
}

type UpdateEnvironmentRequest

type UpdateEnvironmentRequest struct {
	Config    EnvironmentConfig `json:"config,omitempty"`
	IsDefault bool              `json:"is_default,omitempty"`
	Name      string            `json:"name,omitempty"`
	Slug      string            `json:"slug,omitempty"`
}

type UpdateFeatureFlagRequest

type UpdateFeatureFlagRequest struct {
	DefaultValue json.RawMessage `json:"default_value,omitempty"`
	Description  *string         `json:"description,omitempty"`
	Type         string          `json:"type,omitempty"`
}

type UpdateOrgMemberRequest

type UpdateOrgMemberRequest struct {
	Role string `json:"role"`
}

type UpdateOrganisationRequest

type UpdateOrganisationRequest struct {
	DisplayName string          `json:"display_name,omitempty"`
	Metadata    json.RawMessage `json:"metadata,omitempty"`
}

type UpdateOrganisationSecurityPolicyRequest

type UpdateOrganisationSecurityPolicyRequest struct {
	AllowedFactors            json.RawMessage `json:"allowedFactors,omitempty"`
	GracePeriodMs             *int            `json:"gracePeriodMs,omitempty"`
	MfaEnforcement            *string         `json:"mfaEnforcement,omitempty"`
	MfaPolicy                 *string         `json:"mfaPolicy,omitempty"`
	PasswordDisallowReuse     *int            `json:"passwordDisallowReuse,omitempty"`
	PasswordHibpCheck         *bool           `json:"passwordHibpCheck,omitempty"`
	PasswordMaxAgeDays        *int            `json:"passwordMaxAgeDays,omitempty"`
	PasswordMinLength         *int            `json:"passwordMinLength,omitempty"`
	PasswordRequireLowercase  *bool           `json:"passwordRequireLowercase,omitempty"`
	PasswordRequireNumber     *bool           `json:"passwordRequireNumber,omitempty"`
	PasswordRequireSymbol     *bool           `json:"passwordRequireSymbol,omitempty"`
	PasswordRequireUppercase  *bool           `json:"passwordRequireUppercase,omitempty"`
	PreferredFactor           *string         `json:"preferredFactor,omitempty"`
	SessionIdleTimeoutMinutes *int            `json:"sessionIdleTimeoutMinutes,omitempty"`
	SessionTimeoutMinutes     *int            `json:"sessionTimeoutMinutes,omitempty"`
	UnenrolledUserAction      *string         `json:"unenrolledUserAction,omitempty"`
}

type UpdatePasswordPolicyRequest

type UpdatePasswordPolicyRequest struct {
	DisallowReuse    *int `json:"disallowReuse,omitempty"`
	HibpCheck        bool `json:"hibpCheck,omitempty"`
	MaxAgeDays       *int `json:"maxAgeDays,omitempty"`
	MinLength        int  `json:"minLength,omitempty"`
	RequireLowercase bool `json:"requireLowercase,omitempty"`
	RequireNumber    bool `json:"requireNumber,omitempty"`
	RequireSymbol    bool `json:"requireSymbol,omitempty"`
	RequireUppercase bool `json:"requireUppercase,omitempty"`
}

type UpdatePermissionSchemaRequest

type UpdatePermissionSchemaRequest struct {
	// Complete SpiceDB schema definition text
	Schema string `json:"schema"`
}

type UpdateProductRequest

type UpdateProductRequest struct {
	Description    string          `json:"description,omitempty"`
	DisplayName    string          `json:"display_name,omitempty"`
	Metadata       json.RawMessage `json:"metadata,omitempty"`
	SchemaFragment string          `json:"schema_fragment,omitempty"`
	Scopes         []string        `json:"scopes,omitempty"`
	Status         string          `json:"status,omitempty"`
}

type UpdateTokenRuleRequest

type UpdateTokenRuleRequest struct {
	Claims      []TokenRuleClaimMapping `json:"claims,omitempty"`
	Conditions  []TokenRuleCondition    `json:"conditions,omitempty"`
	Description *string                 `json:"description,omitempty"`
	Name        string                  `json:"name,omitempty"`
	Priority    int                     `json:"priority,omitempty"`
	Status      string                  `json:"status,omitempty"`
	Target      string                  `json:"target,omitempty"`
}

type UpdateUserRequest

type UpdateUserRequest struct {
	MetadataAdmin json.RawMessage `json:"metadata_admin,omitempty"`
	Traits        json.RawMessage `json:"traits,omitempty"`
}

type UpdateWebhookRequest

type UpdateWebhookRequest struct {
	Active      bool               `json:"active,omitempty"`
	Events      []string           `json:"events,omitempty"`
	RetryPolicy WebhookRetryPolicy `json:"retry_policy,omitempty"`
	URL         string             `json:"url,omitempty"`
}

type UsageMetrics

type UsageMetrics = UsageResponse

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type UsageResponse

type UsageResponse struct {
	PlanTier string          `json:"plan_tier,omitempty"`
	Quotas   json.RawMessage `json:"quotas,omitempty"`
	TenantId string          `json:"tenant_id,omitempty"`
}

type User

type User struct {
	CreatedAt      string          `json:"created_at,omitempty"`
	Email          string          `json:"email,omitempty"`
	ID             string          `json:"id"`
	MetadataPublic json.RawMessage `json:"metadata_public"`
	Name           string          `json:"name,omitempty"`
	OrgID          string          `json:"org_id,omitempty"`
	State          string          `json:"state"`
	UpdatedAt      string          `json:"updated_at,omitempty"`
}

type UserCreateParams

type UserCreateParams = CreateUserRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type UserList

type UserList struct {
	Data []User `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type UserListParams

type UserListParams = ListParams

UserListParams configures user list queries.

type UserUpdateParams

type UserUpdateParams = UpdateUserRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type UsersService

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

UsersService manages user identities.

func (*UsersService) Create

func (s *UsersService) Create(ctx context.Context, params *UserCreateParams) (*User, error)

Create creates a new user.

func (*UsersService) Delete

func (s *UsersService) Delete(ctx context.Context, id string) error

Delete permanently deletes a user.

func (*UsersService) Get

func (s *UsersService) Get(ctx context.Context, id string) (*User, error)

Get retrieves a user by ID.

func (*UsersService) List

List returns a paginated list of users.

func (*UsersService) ListAll

func (s *UsersService) ListAll(ctx context.Context, params *UserListParams) ([]User, error)

ListAll fetches all users across pages.

func (*UsersService) SendRecovery

func (s *UsersService) SendRecovery(ctx context.Context, id string) (map[string]string, error)

SendRecovery sends a password recovery link to the user.

func (*UsersService) Update

func (s *UsersService) Update(ctx context.Context, id string, params *UserUpdateParams) (*User, error)

Update updates a user.

type ValidationError

type ValidationError struct {
	*APIError
}

ValidationError indicates an HTTP 400 validation_error or HTTP 422 response.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

type Webhook

type Webhook struct {
	Active      bool               `json:"active"`
	CreatedAt   string             `json:"created_at,omitempty"`
	Events      []string           `json:"events"`
	ID          string             `json:"id"`
	RetryPolicy WebhookRetryPolicy `json:"retry_policy,omitempty"`
	UpdatedAt   string             `json:"updated_at,omitempty"`
	URL         string             `json:"url"`
}

type WebhookCreateParams

type WebhookCreateParams = CreateWebhookRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type WebhookDelivery

type WebhookDelivery struct {
	Attempt     int    `json:"attempt"`
	DeliveredAt string `json:"delivered_at,omitempty"`
	DurationMs  int    `json:"duration_ms,omitempty"`
	EventType   string `json:"event_type"`
	ID          string `json:"id"`
	MaxAttempts int    `json:"max_attempts"`
	NextRetryAt string `json:"next_retry_at,omitempty"`
	// Response body from the delivery endpoint (when captured)
	ResponseBody string `json:"response_body,omitempty"`
	Status       string `json:"status"`
	// HTTP status code from the delivery endpoint
	StatusCode int    `json:"status_code,omitempty"`
	WebhookId  string `json:"webhook_id"`
}

type WebhookDeliveryList

type WebhookDeliveryList struct {
	Data []WebhookDelivery `json:"data"`
	// Whether additional pages exist
	HasMore bool `json:"has_more"`
	// Cursor for the next page
	NextPageToken *string `json:"next_page_token,omitempty"`
	// Total count across all pages (when available)
	Total int `json:"total,omitempty"`
}

type WebhookReplayResponse

type WebhookReplayResponse struct {
	OriginalDeliveryId string `json:"original_delivery_id"`
	Replayed           bool   `json:"replayed"`
	// HTTP status code from the subscriber endpoint
	Status  int  `json:"status,omitempty"`
	Success bool `json:"success"`
}

type WebhookRetryPolicy

type WebhookRetryPolicy struct {
	// Initial retry backoff interval in seconds
	InitialIntervalSeconds int `json:"initial_interval_seconds,omitempty"`
	// Maximum delivery attempts before dead-lettering
	MaxAttempts int `json:"max_attempts,omitempty"`
	// Maximum retry backoff interval in seconds (24 hours)
	MaxIntervalSeconds int `json:"max_interval_seconds,omitempty"`
	// Exponential backoff multiplier
	Multiplier float64 `json:"multiplier,omitempty"`
}

type WebhookSubscription

type WebhookSubscription = Webhook

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type WebhookTestParams

type WebhookTestParams = WebhookTestRequest

WebhookTestParams is an alias for WebhookTestRequest (generated from OpenAPI).

type WebhookTestRequest

type WebhookTestRequest struct {
	// Event type to simulate
	EventType string `json:"event_type"`
	// Optional custom event data (defaults to sample payload)
	Payload json.RawMessage `json:"payload,omitempty"`
	// Signing secret (defaults to subscriber secret when subscriber_id is set)
	Secret string `json:"secret,omitempty"`
	// Optional webhook subscriber — URL and secret are inferred when omitted
	SubscriberId string `json:"subscriber_id,omitempty"`
	// Target endpoint URL (defaults to subscriber URL when subscriber_id is set)
	URL string `json:"url,omitempty"`
}

type WebhookTestResponse

type WebhookTestResponse struct {
	Body       string          `json:"body"`
	Error      string          `json:"error,omitempty"`
	Event      json.RawMessage `json:"event,omitempty"`
	Headers    json.RawMessage `json:"headers"`
	LatencyMs  int             `json:"latency_ms"`
	StatusCode int             `json:"status_code"`
	Success    bool            `json:"success"`
}

type WebhookUpdateParams

type WebhookUpdateParams = UpdateWebhookRequest

SDK-friendly aliases for generated OpenAPI types (see generated_types.go).

type WebhooksService

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

WebhooksService manages webhook subscriptions.

func (*WebhooksService) Create

Create creates a new webhook subscription.

func (*WebhooksService) Delete

func (s *WebhooksService) Delete(ctx context.Context, id string) error

Delete deletes a webhook subscription.

func (*WebhooksService) Get

Get retrieves a webhook by ID.

func (*WebhooksService) List

List returns a paginated list of webhook subscriptions.

func (*WebhooksService) ListAll

func (s *WebhooksService) ListAll(ctx context.Context, params *ListParams) ([]WebhookSubscription, error)

ListAll fetches all webhooks across pages.

func (*WebhooksService) ListDeliveries

func (s *WebhooksService) ListDeliveries(ctx context.Context, webhookID string, params *ListParams) (*PaginatedResponse[WebhookDelivery], error)

ListDeliveries returns delivery history for a webhook.

func (*WebhooksService) ReplayDelivery

func (s *WebhooksService) ReplayDelivery(ctx context.Context, deliveryID string) (*WebhookReplayResponse, error)

ReplayDelivery replays a previous webhook delivery.

func (*WebhooksService) Test

Test sends a test webhook delivery to a target endpoint.

func (*WebhooksService) Update

Update updates a webhook subscription.

type WriteRelationshipRequest

type WriteRelationshipRequest struct {
	Relation string          `json:"relation"`
	Resource ObjectReference `json:"resource"`
	Subject  ObjectReference `json:"subject"`
}

Directories

Path Synopsis
Package webhook provides Wocha webhook signature verification and event parsing.
Package webhook provides Wocha webhook signature verification and event parsing.

Jump to

Keyboard shortcuts

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